0

I'm trying to understand how change detection and ChangeDetectionStrategy.OnPush actually work, here is an example of something weird I cannot understand:

plnkr

I create a father component with the following template:

<app-matrix-reader *ngFor="let m of fooService.getMatrices()" [matrix]="m"></app-matrix-reader>

The child component app-matrix-reader has an input text.

<input type="text" [(ngModel)]="matrix.a" /><br/>

If I simply click through the inputs multiple times (even without change its value) the function getMatrices is called.

Why the function getMatrices() is called? I also put changeDetectionStrategy.OnPush so the components should be checked and updated only if their input are updated...

Thank you

user2010955
  • 3,871
  • 7
  • 34
  • 53
  • Angular is just checking if something has changed after going in and out an input, and to check that it needs to take the original values an compare with the current ones – Pablo Lozano Aug 09 '17 at 15:05

1 Answers1

2

Look at this answer

Angular will run change detection cycle whenЖ

...

2) a bound event (like (click) or some host listener) is triggered from the component (that is your case)

If I simply click through the inputs multiple times (even without change its value) the function getMatrices is called.

You're firing blur event on input so angular will mark tree to your component to be checked and execute change detection

yurzui
  • 205,937
  • 32
  • 433
  • 399
  • is there a way to avoid it? – user2010955 Aug 09 '17 at 15:07
  • I don't understand why it happens even with ChangeDetectionStrategy.OnPush, it should set the ChecksEnabled = false, right? – user2010955 Aug 10 '17 at 08:03
  • @user2010955 Angular resets ChecksEnable when handle event https://github.com/angular/angular/blob/master/packages/core/src/view/util.ts#L135 – yurzui Aug 10 '17 at 08:05
  • I see, pfff, my applications creates a lot of children components in a complex multi levels tree and it becomes slow over time, I must understand how change detection really works and skip some useless default change detection cycles – user2010955 Aug 10 '17 at 08:25
  • Look at this answer https://stackoverflow.com/questions/43108155/angular-2-how-to-keep-event-from-triggering-digest-loop/43294113#43294113 – yurzui Aug 10 '17 at 08:53
  • Thank you i'm reading it, I've added a console log in ngDoCheck in my components, and simply scrolling the page or focusing an input text I got 6000 log rows and it reeeeeally slow – user2010955 Aug 10 '17 at 09:00
  • 8000 (or more?) ngDoCheck takes 10 seconds... hmmm – user2010955 Aug 10 '17 at 09:17