Angular: Component Lifecycle Hooks Part 1

Ruchi Vora
6 min readMay 6, 2023

--

Angular Lifecycle Hooks

Angular is a powerful framework for building dynamic and interactive web applications. It provides developers with a wide range of features and tools that make it easier to build robust and scalable applications. One of the key features of Angular is its component lifecycle hooks.

In Angular, a component has a lifecycle that goes through a series of stages or hooks during its creation, update, and destruction. These hooks are methods that Angular calls at specific points in the component’s lifecycle, and they allow you to perform custom logic or actions at those points. You can use the hooks to perform tasks such as data binding, input validation, and event handling.
The various component lifecycle hooks are:

Different types of hooks

In this blog, I will be discussing four lifecycle hooks, they are:

1. ngOnChanges()

ngOnChanges() is called once when the component is first created and then it is called every time when changes are detected in one of the component’s @Input properties. It receives a Simple Changes object as a parameter, which contains information regarding which of the input properties has changed and it also gives its current and previous values and if it is the first change or not.
Consider the following example with the detailed explanation:

Example of ngOnChanges()

Also, if we check the console output, we see the changes object with three properties: i.e currentValue, previousValue and firstChange.

Console output

In the above example, The component has an input property called name, which is bound to an <input> element using the [(ngModel)] directive.

In the ngOnChanges() hook, we're checking if the name input property has changed by looking for it in the changes object. If it has changed, we're generating a new greeting message based on the value of name and setting it to the message property. If name is not provided, we default to using the greeting "Hello, stranger!".

With this implementation, every time the value of the <input> element changes, the ngOnChanges() hook will be called and update the value of the message property accordingly.

If you want, then you can update the message variable only for the first change that occurs when the component is created by checking the firstChange property.

Key point: The ngOnChanges() hook is called only when a component has one or more input properties, and when the value of at least one of these input properties changes.

2. ngOnInit()

ngOnInit() hook is called just once during the component lifecycle, after the first ngOnChanges() call. Even when there are no template-bound @input properties and ngOnChanges() is not called, ngOnInit() is still executed.
It’s common for people to be confused about the difference between the constructor and the ngOnInit() lifecycle hook. So here is the difference:

- constructor: The constructor is not an angular lifecycle hook, it is the typescript specification. The constructor is a default method that’s called automatically when a new instance of a component is created. It’s typically used for basic initialization tasks such as initializing class-level variables or injecting dependencies. At this point the component hasn’t been created yet, only the component class has been instantiated.

- ngOnInit(): It is a lifecycle hook that’s specifically designed for more complex initialization tasks that require access to the component’s input properties and other resources. It’s called after the constructor and after Angular has finished initializing the component’s input properties. This makes it a good place to perform more complex initialization tasks such as retrieving data from a server or setting up subscriptions to observables.

Let's understand the difference with the help of an example:

Example of ngOnInit()
Console Output

In the constructor, we try to access the name property, but it will be undefined at this point because Angular hasn't had a chance to initialize the input property yet. So, we can see that the constructor is not a safe place to access input properties, whereas ngOnInit() is a safe place to access input properties because they have already been initialized by Angular.

3. ngDoCheck()

The ngDoCheck() hook can be considered as an extension of the ngOnChanges() hook in Angular. This method enables you to detect changes that Angular is either unable to detect or will not detect on its own. It gets triggered on every change detection cycle, right after the ngOnChanges and ngOnInit hooks are executed.
This hook is costly since it is called multiple times; after every change detection cycle no matter where the change occurred. Therefore, its usage should be careful to not affect the user experience.
One of the practical applications of ngDoCheck() hook, is to manually mark the component as dirty for mutable objects in onPush change detection strategy.
To gain a better understanding of how the ngDoCheck() hook helps in marking the component as dirty, you can refer to the blog on the onPush change detection strategy.

You can also check this example,

Example of ngDoCheck()

In this example, the component ExampleComponent is configured to use the onPush change detection strategy via the changeDetection property in the component decorator.
The ngOnChanges() hook is implemented to detect changes to the data input and update the message accordingly.
The ngDoCheck() hook is also implemented to manually trigger change detection when the data input changes, but Angular is unable to detect it on its own. The cdr.detectChanges() method is used to manually trigger change detection.

4. ngOnDestroy()

ngOnDestroy() is a lifecycle hook in Angular that is executed just before a component or directive is destroyed, i.e., before it is removed from the DOM. This hook is primarily used to perform any necessary cleanup or unsubscription operations before the component is destroyed, to avoid memory leaks and improve performance.

When a component is destroyed, any subscriptions that it has created to observables, timers, or other resources need to be cleaned up, to prevent memory leaks. ngOnDestroy() provides an opportunity to do this cleanup.

Here is an example of how to use ngOnDestroy() hook to unsubscribe from an observable:

Example of ngOnDestroy()

In the example, we create a subscription to an observable in the constructor. When the component is destroyed, the ngOnDestroy() hook is called and we unsubscribe from the observable to avoid any memory leaks.

It is important to note that ngOnDestroy() is not called when a component is removed from the DOM due to a route change. However,ngOnDestroy() is called only when the component is removed from the Angular application altogether.

I hope that this blog has provided you with a clear understanding of the various Angular lifecycle hooks and their applications. In my next blog, I will discuss the remaining lifecycle hooks in detail.

Until then be happy and stay healthy!!!!!
Also, feel free to comment down below, if you have any doubts or suggestions…..

--

--