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

1.2K    Asked by SanjayDutt in Python , Asked on Nov 12, 2019
Answered by Arun Singh

Angular bootstrap process consists of the two major stages:

constructing components tree

running change detection

The constructor of the component is called when Angular constructs components tree. All lifecycle hooks are called as part of running change detection.

When Angular constructs components tree the root module injector is already configured so you can inject any global dependencies. Also, when Angular instantiates a child component class the injector for the parent component is also already set up so you can inject providers defined on the parent component including the parent component itself. Component constructors is the only method that is called in the context of the injector so if you need any dependency that's the only place to get those dependencies.

When Angular starts change detection the components tree is constructed and the constructors for all components in the tree have been called. Also, every component's template nodes are added to the DOM. The @Input communication mechanism is processed during change detection so you cannot expect to have the properties available in the constructor. It will be available after ngOnInit.



Your Answer

Interviews

Parent Categories