Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Log the number of change detections in Angular (Globally)

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
like image 380
Royi Namir Avatar asked Jun 21 '18 08:06

Royi Namir


People also ask

How many change detectors are there in Angular?

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.

What does ChangeDetectorRef detectChanges () do?

detectChanges()link Checks this view and its children. Use in combination with detach to implement local change detection checks.

How do you detect change detection?

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.

What is the use of ChangeDetectorRef in Angular?

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.


1 Answers

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();
}
like image 94
fjc Avatar answered Sep 21 '22 19:09

fjc