ExpressionChangedAfterItHasBeenCheckedError - Expression has changed after it was checked
Expression has changed after it was checked
參考鏈接
一個(gè)能夠完美重現(xiàn)該問(wèn)題的例子:
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構(gòu)建過(guò)程中,試圖修改一個(gè)我們?cè)敬蛩泔@示在視圖上的數(shù)據(jù),導(dǎo)致了這個(gè)錯(cuò)誤。
解決方法:
把賦值操作包裹到setTimeout里即可:
setTimeout能夠工作的原因
Angular then finishes rendering the view and reflects the latest data changes on the screen, and the Javascript VM turn completes
更多Jerry的原創(chuàng)文章,盡在:“汪子熙”:
總結(jié)
以上是生活随笔為你收集整理的ExpressionChangedAfterItHasBeenCheckedError - Expression has changed after it was checked的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: SAP Spartacus cxFocu
- 下一篇: LOL凯尔大乱斗出什么装 s12天使天赋