Introduction

Any component that is created has a lifecycle (e.g. initialization, change, destruction). Angular provides hooks that allow us to access components at certain points during its lifecycle. In this blog post, we will discuss the different lifecycle hooks, what they do and when to use them.

NOTE: The lifecycle hooks below are listed in order of how Angular will execute them.

Constructor()

Constructors are part and parcel of a class. They initialize an object, which is an instance of a class. Angular calls these constructors once an instance of a component is created used the keyword new.

OnChanges

OnChanges is another hook that is part of the Angular lifecycle. This hook is called when when data that is bound to a property using a directive changes. OnChanges is an interface that is implemented in a component the same way as OnInit. The ngOnChanges() method is used to carry out actions once a change occurs.

OnInit

OnInit is an interface which is implemented in a component and is called after the initialization of a component. The ngOninit() method can be used to initialize anything else that you need to have after the component has been initialized. OnInit is called only once at the beginning when a change is detected.

The difference between OnInit and Constructor() is that the constructor is called during bootstrapping. That is, when Angular instantiates components, directives, services, and pipes. OnInit on the other hand, is dealt with when Angular detects a change right after bootstrapping. Change detection occurs when there has been a change of either a directive or a component in terms of its state. Angular then deals with that change by updating the DOM.

DoCheck

DoCheck is another method that is involved in change detection. It runs after Angular’s default change detector has ran. It is a callback method.

DoCheck differs from OnChanges and OnInit. It is not an event-based hook. Rather, it is a hook that can be leveraged by the developer to add his/her own code for change detection. In order to use DoCheck, we have to implement it like we do with OnChanges and OnInit. We then can insert our code using the ngDoCheck() method. Unlike OnChanges, DoCheck does not need a condition in order to run. This means that Angular does not need to detect a change for DoCheck to run. You should not use it and OnChanges to deal with changes on the same element.

OnDestroy

OnDestroy is used when destroying a pipe, service, or directive. OnDestroy is used to cleanup instances of the above once they are destroyed. It is also used when unsubscribing from observables and when dissociating from event handlers. This is done to prevent memory from leaking.