Angular lifecycle hooks: NgOnInIt

Joshua Markasky
3 min readJan 27, 2021

Lifecycle hooks in angular are really simple but I don’t think there’s a lot of good explanation showing what they do and how to use them. So I’m going to be going though each one individually with some example on how and when to use them.

Lets start with the easiest one we can talk about, NgOnInit. The idea of it is relatively simple. Its a function that run when a component becomes instantiated. So right when a component comes in the document, it will run this function and whatever code is written inside of it.

The Most common use case for this, is to set variables to certain values when the component first starts up. Like maybe we are creating a form with a edit functionality where we allow the user to edit information to change in the data base. lets used that example

Here we have a simple form with a input component and a place holder. So lets just set the value of each input when the component starts up.

you can see in the NgOnInIt we simple just set the values of the variables and we can now see those values in the inputs. Simple enough right? Of course you wouldn’t be hard coding that data in like that, You would be making calls to a database and there you can in fact run into some asynchronous issue’s but that's more of a javascript problem then Angular itself. In the future ill cover more on that to avoid the infamous call back hell you can get into with javascript. Till then

Connect with me on linkedIn: www.linkedin.com/in/joshua-markasky47

follow me on Twitter: https://twitter.com/MarkaskyJ

Checkout my YouTube channel: https://www.youtube.com/channel/UCgRkJcniRghYpSpzKQlEYvQ

--

--