What is the difference between ngOnInit and Constructor

Asked

Viewed 388 times

0

The problem I encountered was the following: Needed to validate a token when the page was started if the token was validated then it would be visible a second Forms if not just the first Forms where I would call this function? in the ngOnInit or in the constructor?

If the angle already provides the ngOnInit pq there is also a constructor?

When should I use the ngOnInit or the constructor?

1 answer

4


The problem I came across was this: I needed to validate one token when the page was started if the token was then validated would be visible a second Forms if not only the first Forms where would I call that function? in ngOnInit or constructor?

In the ngOnInit, because it can be used precisely for this type of thing, avoid logic in the constructor.

If the angular already provides ngOnInit pq there is also a constructor?

Two things for different purposes:

The constructor is the default method of the class. In Angular it is mainly used to inject dependencies into the component

The ngOnInit is part of the component’s life cycle. A common practice is to use it for initialization of component logic.

When to use ngOnInit or constructor?

Usually the two are used together, because each has a different purpose, as stated earlier.

Interesting article that talks a little about

Browser other questions tagged

You are not signed in. Login or sign up in order to post.