我有一个<input>
字段和一个组件,它们绑定了一个通用模型。我ngOnChanges()
在组件中使用来检查该输入的值,并且我正在更改绑定到该组件中某处的该输入的模型。
假设我们date
将变量绑定到<input>
和组件。在这种情况下会发生错误:
input field changed (also date changed)
--> ngOnChanges
--> new value of date doesn't fit requirements
--> change the date to something else
--> <input> emits the new date
--> ngOnChanges() triggered again
--> ExpressionChangedAfterItHasBeenCheckedError
以下是我的部分代码:
app.component.html
:
...
<input [(ngModel)]="date">
<app-date-picker [date]="date" (dateUpdated)="setDate($event)"></app-date-picker>
...
app.component.ts
:
setDate(newDate: Date): void {
this.date = newDate.toISOString().split('T')[0];
}
date-picker.component.ts
:
ngOnChanges(changes: SimpleChanges): void {
if (changes.date) ... // Do some checks
if (invalidDate) {
...
this.select(newDay);
}
}
select(d: number): void {
this.selectedYear = this.year;
this.selectedMonth = this.month;
this.selectedDay = this.day = d;
this.dateUpdated.emit(new Date(this.year, this.month, this.day + 1));
}