'How to display Angular9 change detection process in browser?
I have a complex component with many @Input() and async process. I want to optimize the component, thus intend to analyze Angular4 change detection cycle upon my component.
May I know how to identify if the Angular4 change detection system is being triggered, and the DOM is being re-rendered?
Probably, using console.log(...)
?
Typically, I hope for something like (in browser console):
Change-detection running... no changes... 1
Change-detection running... no changes... 2
Change-detection running... no changes... 3
Change-detection running... no changes... 4
Change-detection running... changed
No DOM rendering
Change-detection running... no changes... 5
Change-detection running... no changes... 6
Change-detection running... changed
DOM re-rendered
Change-detection running... no changes... 7
Change-detection running... no changes... 8
How do I achieve this? Or how do you guy optimize the Angular4 performance? Any other approaches?
Solution 1:[1]
i wanted to do the same but there is no lifecycle hook which can do that, so i did a hack, may be that will help you as well.
on any tag in the html template invoke a function and log on console when the function is executed. Whenever the change detection will be executed, the template will get re-evaluated resulting in the function invocation. That worked pretty well for me to analyze what's going
.html
<div>{{doNothing()}}</div>
.ts
doNothing() {
console.log('template evaluated');
}
Solution 2:[2]
If you have a ngFor in your template you can add trackBy. This will get called every time change detection triggers (https://angular.io/api/common/NgForOf#change-propagation) and you can log out a statement. You can then set a breakpoint on the function and look at stack trace to see where change events are originating.
I stumbled across this method while trying to debug an issue that would crash the browser due to change detection getting constantly triggered.
template
<div *ngFor="let things of things; trackBy: trackThings"></div>
component
trackThings(index, thing) {
console.log(index, question)
return thing ? index : undefined;
}
Track by also improves performance: https://medium.com/@ramy_ali/improving-angular-ngfor-performance-through-trackby-ae4cf943b878
Solution 3:[3]
The Angular DevTools for Chrome provide a profiler that lists all change detection events, shows the source for each event and also allows you to see which component has been checked during each CD cycle. Just make sure to select the "flame graph" and tick the "Show only change detection" checkbox. The components marked blue have been checked.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Suresh Nagar |
Solution 2 | |
Solution 3 | slim |