5

In angular, is it possible to hook to ngOnInit event for each component?

for example I want to execute console.log('im on ngOnInit');, in every component in my application, and I do not want to open each component and write this in the code.

Something like this or similar way is possible to do?

main.ts

 import { component } from '@angular...';
 
 component.hook('ngOnInit', (cmp) => { console.log('im on ngOnInit'); });
Jon Sud
  • 10,211
  • 17
  • 76
  • 174
  • Does this answer your question? [Angular 2: "Global" lifecycle hooks?](https://stackoverflow.com/questions/39420241/angular-2-global-lifecycle-hooks) – tommueller Nov 08 '20 at 17:22
  • no, because I need to add `Lifecycled` to each of my components. I want in one place to hook every component (even those are lazy loaded) – Jon Sud Nov 08 '20 at 17:24
  • I neither think that is possible nor that it would be a good idea ;) – tommueller Nov 08 '20 at 18:53
  • why not? what do you sugges when I need to do some logic (say console.log) and I want to have it in every component and I need to apply that to ten of thousands components in my application. I don't want to write in each component `console.log`. so I looking for a wide solution. – Jon Sud Nov 08 '20 at 19:11
  • Can be done via Global service implementation which can be registered at `APP_INITIALIZER` to the providers list. In order to run custom logic before each component is initialised. – khizer Apr 03 '23 at 01:06

0 Answers0