ExpressionChangedAfterItHasBeenCheckedError - Expression has changed after it was checked
生活随笔
收集整理的這篇文章主要介紹了
ExpressionChangedAfterItHasBeenCheckedError - Expression has changed after it was checked
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Expression has changed after it was checked
參考鏈接
一個能夠完美重現該問題的例子:
export class BankAccount implements OnChanges{ngOnChanges(changes: SimpleChanges): void {/*console.log('ngOnChanges triggered: ' + changes.bankName.currentValue + ' previous value: ' + changes.bankName.previousValue);*/}// This property is bound using its original name./*@Input()set bankName(newName) {console.log('bankName new value set: ' + newName);}*/@Input()bankName:string;// this property value is bound to a different property name// when this component is instantiated in a template.@Input('account-id') id: string;// this property is not bound, and is not automatically updated by AngularnormalizedBankName: string; }@Component({selector: 'app',template: `<bank-account [bankName]="bankName" account-id="4747"></bank-account>` }) export class App implements OnInit, AfterViewInit{_bankName = 'Jerry';ngAfterViewInit(): void {this._bankName = 'Jerry2';}get bankName(){return this._bankName;}ngOnInit(): void {}}root cause
The problem here is that we have a situation where the view generation process (which ngAfterViewInit is a part of) is itself further modifying the data that we are trying to display in the first place:
在view構建過程中,試圖修改一個我們原本打算顯示在視圖上的數據,導致了這個錯誤。
解決方法:
把賦值操作包裹到setTimeout里即可:
setTimeout能夠工作的原因
Angular then finishes rendering the view and reflects the latest data changes on the screen, and the Javascript VM turn completes
更多Jerry的原創文章,盡在:“汪子熙”:
總結
以上是生活随笔為你收集整理的ExpressionChangedAfterItHasBeenCheckedError - Expression has changed after it was checked的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: SAP Spartacus cxFocu
- 下一篇: LOL凯尔大乱斗出什么装 s12天使天赋