DEV Community

Cover image for ANGULAR COMPONENT LIFECYCLE HOOK METHODS YOU SHOULD KNOW
Alphaexcel
Alphaexcel

Posted on

ANGULAR COMPONENT LIFECYCLE HOOK METHODS YOU SHOULD KNOW

First, let’s break down the two major words here which are “Lifecycle” and “Hook”.
• Lifecycle encompasses the stages that the component
undergoes from its creation to its destruction which would
mean death when we talk about a living organism.
• Hook categorizes the different breakpoints that the
component passes through from when it was created.
*

WHAT IS THE ANGULAR LIFECYCLE HOOK*

A component instance has a lifecycle hook that starts when Angular instantiates a component class the minute you create an application and renders the component view along with its child views.
A lifecycle continues with change detection, that is a change occurs that is also part of the lifecycle of a component.
It updates both views and the component instances as needed as it checks to see what data-bound properties change.
The lifecycle ends when Angular destroys the component instance and it removes the rendered templates from the DOM.
You can check more on the DOM https://medium.com/@ojigbareoyinemi2/dynamics-of-a-basic-counter-javascript-project-5690426a86da
NB: Directives can also have lifecycle hooks.
This is a list of lifecycle hooks in Angular:
ngOnChange()
ngOnInit()
ngDocheck()
ngAfterContentInit()
ngAfterContentChecked()
ngAfterViewInit()
ngAfterViewChecked()
ngOnDestroy()

You need to know these three life cycle methods out of the eight:
ngOnChange() **: This occurs whenever anything on a
component changes this lifecycle method is called or used.
• **ngOnInit()
: This is the most commonly used lifecycle
method it is present immediately after you create the
application on angular CLI.
Whenever we load any component the constructor is called next then the ngOnInit() is called.
Constructor: A constructor is basically a part of a class.
What happens when you create a component using Angular is it initiates a class, then when a class is initiated then the constructor is called after those properties are added then the constructor is called after the properties are added then the view is loaded. Then when this process is completed and the constructor is ready to mount, then the ngOnInit lifecycle is created. This ngOnInit means when the component is ready to be mounted on the HTML of the DOM. That’s why it’s called after the constructor.
ngOnDestroy(): This helps repeated instances or loops
in the component lifecycle to be ended easily. When this
component lifecycle is called or used.

Conclusion

You may not necessarily use all of this Angular component lifecycle hook but the three explained will be essential for your daily usage as you build applications using angular framework.
Happy Coding.

Top comments (0)