Problem with detecting changes - why does it change when it refers to the same On Push object reference

It seemed to me that I understood quite clearly how the Angular change detection function works after this discussion: Why doesn't change detection happen here when [value] is changed?

But look at this plunge: https://plnkr.co/edit/jb2k7U3TfV7qX2x1fV4X?p=preview

@Component({ selector: 'simple', template: ` <div (click)="onClick()"> {{myData[0].name}} </div> `, changeDetection: ChangeDetectionStrategy.OnPush }) export class Simple { public @Input() myData; constructor() { } public onClick() { } } 

Press a, it changed to c

I understand that the click event triggers application-level change detection, but [myData] = "testData" still refers to the same object, and I use On Push on Simple, why has it changed?

+7
angular
Feb 18 '17 at 6:49
source share
1 answer

What about the design.

If you have a component that detects OnPush changes, then its detectChangesInternal function detectChangesInternal not run unless one of four things happens:

1) one of his @Inputs changing

~ 2.4.x enter image description here

~ 4.xx enter image description here

Note. @Input should be represented in the template. See Question https://github.com/angular/angular/issues/20611 and comment

2) the related event is fired from the component ( which is your case )

Caveats: there is a difference between 2.xx and 4

Angular ChangeDetectionStrategy.OnPush with child component emitting event

~ 2.4.x enter image description here

~ 4.xx enter image description here

3) you manually mark the component to be checked ( ChangeDetectorRef.markForCheck() )

4) asynchronous calls to ChangeDetectorRef.markForCheck() internally

 private _updateLatestValue(async: any, value: Object): void { if (async === this._obj) { this._latestValue = value; this._ref.markForCheck(); } } 

https://github.com/angular/angular/blob/2.4.8/modules/%40angular/common/src/pipes/async_pipe.ts#L137




In other words, if you install OnPush for a component, then after the first status of the verification component is changed from CheckOnce to Checked , and after that it waits until we change the status. This will happen in one of the three things above.

See also:

There are also good explanations of how angular2 change detection function works:

Here is a Live Example (thanks to Paskal) that explains OnPush detecting changes. ( Comp16 looks like your component. You can click on this frame)

+10
Feb 18 '17 at 7:09
source share



All Articles