简体   繁体   中英

EventEmitter not emitting value back to form

I'm trying to get the updated date value back from the form but it's not working:

@Component({
    selector: 'date-picker',
    template:
    `   
        <select [(ngModel)]="day" name="dayPicker" class="form-control" style="width: 80px" required>
            <option *ngFor="let day of days" [value]="day">{{day}}</option>
        </select>
        <select [(ngModel)]="month" name="monthPicker" class="form-control" style="width: 80px" required>
            <option *ngFor="let x of months" [value]="x.MonthId">{{x.MonthName}}</option>
        </select>
        <select [(ngModel)]="year" name="yearPicker" class="form-control" style="width: 100px" required>
            <option *ngFor="let year of years" [value]="year">{{year}}</option>
        </select>
    `,
    providers: [
        {
            provide: NG_VALUE_ACCESSOR,
            useExisting: forwardRef(() => DatePicker),
            multi: true,
        }
    ]
})

export class DatePicker implements ControlValueAccessor, OnChanges, OnInit  {

public _day: number = null;
public _month: number = null;
public _year: number = null;

@Input() public inputDate: Date;
@Input() public yearBegin: number;
@Input() public yearEnd: number;

@Output() public dateChange: EventEmitter<Date> = new EventEmitter<Date>();

private months: Month[];
private years: number[];
private daysInMonth: DaysInMonth[];
private days: number[];

private onChangeCallback: (_: any) => {};
private propagateChange = (_: any) => {};

so when i say change the year:

set year(val: number) {
    this._year = val;
    if(this._day != null && this._month != null) {
        this.inputDate = new Date(this._year, (this._month - 1), this._day);
        this.dateChange.emit(this.inputDate);
        this.propagateChange(this.inputDate);
    }
}

this is how I use it:

<form #personalInfoForm="ngForm" (ngSubmit)="onSubmit()" class="form-width">
<date-picker [(inputDate)]="parsedDate" name="BirthDate" [yearBegin]="1950" [yearEnd]="2020"> </date-picker>
</form>

When I change the date values around in the dropdowns and press the form's submit button I do not see the updated date. It's the same date my custom date picker control got initialized with.

I don't see anything listening for that EventEmitter.

You want something like (dateChange)="onDateChange($event.value)" Where onDateChange($event.value) is a method in the parent componenet which accepts the new value.

The angular documentation has a nice and simple example of this: https://angular.io/guide/component-interaction#parent-listens-for-child-event

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM