Angular change detection and resolution Error: NG0100: ExpressionChangedAfterItHasBeenCheckedError: Expression has change

question

Recently encountered a problem:
insert image description here

Finally found a solution here: https://angular.io/errors/NG0100.
insert image description here

insert image description here

Trigger change detection manually:
insert image description here

Trigger change detection via an asynchronous operation:
insert image description here
insert image description here

Summarize:
.....

change detection

What change detection?

By detecting changes between the view and the state, after the state changes, it helps us update the view. This mechanism of synchronizing the view with our data is called change detection.

What triggers change detection?

Asynchronous operations trigger change detection. for example:

  • When a click event (browser event) is fired.
  • http request.
  • Timer: setInterval(), setTimeout().
  • Promise.resolve().then(() => {});

life cycle hook

essence

  • 生命周期一直伴随着变更检测, Angular checks for changes to data-bound properties and updates the view and component instances as needed.
  • Lifecycle 开始: The lifecycle of a component instance begins when Angular instantiates the component class and renders the component's view and its subviews.
  • Lifecycle 结束: The lifecycle ends when Angular destroys the component instance and removes the template it rendered from the DOM.

order of execution

hook illustrate
withOnChanges() The invocation of this hook will be triggered when the value of @Input()the modified attribute changes. Otherwise it will not be called.
withOnInit() After Angular first displays the data binding and sets the directive/component's input properties 初始化指令/组件. It will definitely be called and only called once.
ngDoCheck() 自定义变更检测逻辑
ngAfterContentInit() Called after Angular has projected external content into the component's view or the view in which the directive resides.响应内容中的变更
ngAfterContentChecked() 响应被投影内容的变更
ngAfterViewInit() Called after Angular has initialized the component view and its subviews or the view containing this directive.响应视图变更
ngAfterViewChecked()
ngOnDestroy()

Learning Resources

Angular Change Detection Detailed Explanation
NG0100: Expression has changed after it was checked

https://blog.angular-university.io/angular-debugging/

Guess you like

Origin blog.csdn.net/Kate_sicheng/article/details/128154256