I need to see how many change detection cycles are running in my app ( and who initiated it) - which has many many components.
Currently , I know that , at each component , I can use the ngDoCheck
method :
ngDoCheck()
Detect and act upon changes that Angular can't or won't detect on its own. Called during every change detection run, immediately after ngOnChanges() and ngOnInit().
This is not a bad solution.
Question:
But - is there a way to do it globally ? I mean , I really don't want to modify each component and add this code.
Is there a way that the "listener & Logger" will be in a global scope so that i'll know which part of my app causes many change detection cycles?
My goal (if possible) :
(console.log) -- from component A
(console.log) -- from component A
(console.log) -- from component A
(console.log) -- from component B
(console.log) -- from component C
(console.log) -- from component C
There are two types of change detection: default change detection: Angular decides if the view needs to be updated by comparing all the template expression values before and after the occurrence of an event, for all components of the component tree.
detectChanges()link Checks this view and its children. Use in combination with detach to implement local change detection checks.
The answer is using observables. 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.
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.
AfterViewChecked
should help you:
Respond after Angular checks the component's views and child views / the view that a directive is in. Called after the ngAfterViewInit and every subsequent ngAfterContentChecked().
If you implement AfterViewChecked
in your AppComponent
, it should fire every time any change happens in any of the child components:
ngAfterViewChecked() {
console.trace();
}
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