On generating an Angular project using the CLI, the root component - AppComponent does not have an ngOnInit block but every other component generated has an ngOnInit block. Is it wrong to have an ngOnInit in the root component?
ngOnInit: OnInit is a life cycle widget called Angular to show that Angular is made to create a component. We have to import OnInit like this to use it (actually using OnInit is not mandatory but it is considered good).
By looking at the logs in console it shows that only ngOnDestroy get's called on the service but not ngOnInit . So, we now know that Angular services has ngOnDestroy life cycle hook which we can use to do any clean up work like we do in components and directives.
The constructor() should only be used to initialize class members but shouldn't do actual "work". So we should use constructor() to setup Dependency Injection, Initialization of class fields etc. ngOnInit() is a better place to write "actual work code" that we need to execute as soon as the class is instantiated.
OnInit 's primary purpose, according to the Angular Docs is to “Initialize the directive/component after Angular first displays the data-bound properties and sets the directive/component's input properties. Called once, after the first ngOnChanges().”
There's nothing wrong to have an ngOnInit in the root component. But there is no need.
By the definition, root component is just called once like <app-root></app-root>
in the index.html. And not called by any other components. thus, root component would not have @Input()
bindings that ngOnInit
assured set properly.
not-viable.component.html:
<app-root [someInput]="variable"></app-root>
Conclusion
You can have ngOnInit
in the root component, but constructor
can do the same thing without any flaw.
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