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.
Input Reference But with OnPush strategy, the change detector is only triggered if the data passed on @Input() has a new reference. This is why using immutable objects is preferred, because immutable objects can be modified only by creating a new object reference.
To run the change detector manually: Inject ChangeDetectorRef service in the component. Use markForCheck in the subscription method to instruct Angular to check the component the next time change detectors run. On the ngOnDestroy() life cycle hook, unsubscribe from the observable.
Change detection is the process through which Angular checks to see whether your application state has changed, and if any DOM needs to be updated. At a high level, Angular walks your components from top to bottom, looking for changes.
ChangeDetectorRef allows you to manipulate this tree, angular runs the change detection every time there is a change. For example, when you have a large amount of data and there is a change in that data, angular will render the view again, if the data changes every second, your application will become slower.
If you want "manual" change detection, use ChangeDetectorRef.detach() rather than OnPush
. You might want to do this if you have a component with (a lot of) data that is changing very frequently, hence you want/need to control how often change detection runs (i.e., when the view is updated) so that the user interface remains responsive (i.e., the browser doesn't get bogged down with too much change detection).
The above use case is rare, and you probably want to use OnPush
to limit how often change detection runs on your component, rather than go all the way to fully manual change detection. @Günter already covered OnPush
in his answer.
is there any way to check if its working as expect and no change detection is performed on a particular component
Yes, implement ngDoCheck()
and put a console.log()
inside it. This method is called whenever change detection runs on your component/directive.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With