Can we implement logic for all the Angular component ngAfterViewInit method?

262 Views Asked by At

All, I am looking a generic way to implement ngAfterViewInit method for all the components in a big web application.

The reason is we need to track each page's loading time, so in order to do this, I need to put checking solution into ngAfterViewInit method for the components to be checked.

The problem is there are too many components and too many pages, if I use either abstract class or put logic directly into the method, I have to touch all the components and update one by one, this is not generic at all.

So I am wondering if there are some generic solutions to add logic in just one place and being called by all the components automatically.

1

There are 1 best solutions below

0
On BEST ANSWER

Probably not the answer you're wanting to hear, but there isn't a way to define that behavior or tap into all of your components from a module level. Would be neat, for sure!

The problem is that the AfterViewInit functionality triggers independently when the component hits that stage of the lifecycle hook; technically the module the component belongs to doesn't know when that occurs.

Without extending a basic class that is extended by all of your components, it won't be possible. What I will say is that you can grind through all of that pretty easily if you create all of that functionality in one class and just implement the functionality that you need in that. The other thing to do is to possibly tap into a service or a guard and cut the hard work in half. You can initialize whatever you need inside of an app_initializer and watch for route changes?