2

I m studying Angular 2 change detection and I'm having some trouble, or at least, I need to some explanations.

Let's get the following simplified code from AppRef (and from Througtram blog) :

class ApplicationRef {

  changeDetectorRefs:ChangeDetectorRef[] = [];

  constructor(private zone: NgZone) {
    this.zone.onTurnDone
      .subscribe(() => this.zone.run(() => this.tick());
  }

  tick() {
    this.changeDetectorRefs
      .forEach((detector) => detector.detectChanges());
  }
}

We can assume that there's one changeDetector by component. I'm assuming too that there is only one Zone.js fork used in one angular 2 application.

From now, let's get the code implementation of detectChanges, where there is a comparison such as (simplified) :

detectChanges(){
  //...
 if(this.previousValue !== newValue){
   this.previousValue = newValue
 }

}

From that point, knowing that only one Zone.js fork will trigger all the events and then start a changeDetection cycle, does it mean that all the detectors from all the component tree will be concenered by this comparison ? I mean, if I have 1000 components, will I'have 1000 calls to detectChanges ?

Thanks for your help

1 Answer 1

2

Basically yes, Angular compares every binding from top to bottom on each change detection cycle.

This is why there is ChangeDetectionStrategy.OnPush which allows to skip checking components (and its child/descendant components and directives) when no input property was changed for this component.

Sign up to request clarification or add additional context in comments.

2 Comments

One last thing, where is the previous state stored for comparison ? I guess that after a change detection cycle, there's a comparison that have to say if change detection is to apply or not. Do you know where it's located in the source code ?
Sorry, didn't stumble upon this yet. Sometimes differs that are used like in ngOnChanges/ngDoCheck like in ngFor github.com/angular/angular/blob/… but for component properties, I don't know. I guess somwhere in the component.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.