What is the exact meaning of component initialization in angular 2+, when we talk about OnInit?

2.9k Views Asked by At

According to Angular.io Angular Documentation on Life cycle hooks The purpose of OnInit : Initialize the directive/component after Angular first displays the data-bound properties and sets the directive/component's input properties.

So what exactly happens when it is said component has initialized. Does it mean all the variables are initialized or the component's template is displayed or both?

2

There are 2 best solutions below

2
On

So what exactly happens when it is said component has initialized. Does it mean all the variables are initialized or the component's template is displayed or both?

Markup is rendered, bindings are bound, NO child view/components are injected. In other words, you can start initializing your component in context of its inputs. You can threat it as "Angular Construction" method and do all component initialization stuff there. It is very similar to @PostConstruct concept from EJB.

1
On

ngOnInit is useful after angular is done with creation of the component. So, when constructor finishes its work, the component is said to be initialized and it has specified properties which you can initialize in ngOnInit now.

I hope this helps!