前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >ExpressionChangedAfterItHasBeenCheckedError - Expression has changed after it was checked

ExpressionChangedAfterItHasBeenCheckedError - Expression has changed after it was checked

作者头像
Jerry Wang
发布2021-02-24 12:18:10
7310
发布2021-02-24 12:18:10
举报

Expression has changed after it was checked

参考链接

一个能够完美重现该问题的例子:

代码语言:javascript
复制
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 Angular
  normalizedBankName: 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

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2021-01-13 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • root cause
  • setTimeout能够工作的原因
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档