Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't the AppComponent have an ngOnInit function by default?

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?

like image 753
Karma Avatar asked Mar 25 '17 14:03

Karma


People also ask

Is ngOnInit required?

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).

Does Angular service have ngOnInit?

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.

Why should ngOnInit be used if we already have a constructor?

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.

What is the primary reason of using ngOnInit hook?

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().”


1 Answers

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.

like image 196
zmag Avatar answered Oct 09 '22 01:10

zmag