In Angular2, why is there 2 times to check the contents and view after setTimeout?

Here is my code

@Component({ template: `<h1>Hello from A</h1> <ul> <li *ngFor="#letter of letters; #i = index"> <button (click)="appendW(i)">{{letter | uppercase}}</button> </li> </ul> <button (click)="doSomething()">Click</button>`, pipes: [UpperCasePipe], directives: [NgFor] }) export class AComponent { letters = ['a','b','c','d']; contructor(){ } appendW(index) { // console.log(letter); setTimeout(()=>{ this.letters[index] += "W"; }, 1000) } ... } 

Plnkr

After setTimeout, angular double-checks the content and view. Can anyone explain this? Why does angular need to check TWICE?

+3
source share
1 answer

Angular uses zones to know when an event is fully processed by fixing some asynchronous APIs such as (addEventHandler, setTimeout, ...), and then triggers change detection after each event.

In dev mode, Angular runs the next change detection immediately after the first. Since there was no event between events, no change should have occurred.

If the model has still changed, Angular considers this a possible mistake.

Possible reasons:

  • The field, getter, or function that the view is associated with each time returns a different instance that is recognized as a change.
    Often this happens with functions that return a filtered subrange of the array. This subrange must be bound to the field and return the same cached instance if the filter criteria has not changed.
    Angular only compares the identifier of the previously and currently returned array and ignores whether the contents of the array (or other objects) remain the same.

  • Code that was triggered by an event that was not logged in the Angulars patch zone caused a model change.
    This is usually caused by third-party libraries that are not initialized within Angular. Either initialize them in Angular, if possible, or notify Angular of the change ( Triggering Angular2 manually change )

In production mode, Angular is simply checked once and possible side effects are ignored.

+11
source

Source: https://habr.com/ru/post/1269345/


All Articles