Angular - 关于绑定的ExpressionChangedAfterItHasBeenCheckedError

时间:2017-06-06 08:48:05

标签: angular typescript ngonchanges

我有一个<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));
  }

1 个答案:

答案 0 :(得分:0)

我通过超时更改日期解决了这个问题:

ngOnChanges(changes: SimpleChanges): void {
  if (changes.date) ... // Do some checks
  if (invalidDate) {
     ...
     setTimeout(() => { select(newDay); }, 50);
  }
}