Search code examples
angularangular2-templateangular2-directivesangular2-changedetection

How to check if Change Detection was triggered on a component


In my app I want to set manual change detection. For this I set the ChangeDetectionStrategry to OnPush and whenever a change occurs in a component I manually run change detection using detectChanges.

If I set ChangeDetectionStrategy to OnPush on a parent component, as per my understanding it will run change detection only once on the parent component and only once on the child component, even if I don't set ChangeDetectionStrategy to OnPush on child. If there is any change in the parent component, I run detectChanges() in parent component. And if there is any change in the child component, I run detectChanges() in child component.

Please suggest is it the correct way? or is there any better way?

Secondly, is there any way to check if its working as expect and no change detection is performed on a particular component.


Solution

  • With ChangeDetectionStrategy.OnPush, change detection is run in the child component when an @Input()s value of the child component was updated, an event the child component was listening to was received (someEvent)="..." or @HostListener(...) or an observable bound to using the | async pipe emitted an event.

    To run code when @Input() was changed you can make the input a setter or implement OnChanges for code to be executed on updates.

    For events, just call your code in the event handler.

    For observables you can apply an operator like .map(...) for your code to be executed when values are emitted.