Angular: Lifecycle hooks and their practical usage
Tags: javascript, angular, typescript, webdev
Published: 2022-06-03 16:04:06

Any Angular project is just a bunch of components that serves the specific feature of application and each and every component follows a lifecycle that starts when Angular instantiates the component class and renders the view along with its child view. 

In this post we will try to understand how can we as a developer implement the life cycle hooks in our application.

After the application instantiate a component by calling the constructor, Angular starts calling the lifecycle hooks which is implemented by you in the lifecycle of that component instance.

![Angular Lifecycle hooks](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xwlabfng6eg4mm6kzufp.png)
 

> **Note: constructor is the feature of TypeScript, so Angular does not treat this as a part of lifecycle hooks.**

Angular executes hooks methods in the following sequence:

```
- ngOnChanges()
- ngOnInit()
- ngDoCheck()
- ngAfterContentInit()
- ngAfterContentChecked()
- ngAfterViewInit()
- ngAfterViewChecked()
- ngOnDestroy()
```
<u>**ngOnChanges()**</u>: A lifecycle hook that is called whenever any data bound property gets change. This is the first lifecycle hook that gets executed whenever a component gets instantiated. This method also receives a **SimpleChanges** object of current and previous property values. ngOnChanges() method called on every update of **@input()** properties. The biggest advantages of using ngOnChanges() is that you will get all changes at once if your component has more that one **@input()** properties. 

``Note: If your component doesn't have any @input() property then angular will never call ngOnChanges() even though you're using it.``
**Syntax:**

```javascript
ngOnChanges(changes: SimpleChange): void {
    let currentChange = changes.currentValue;
    let previousChange = changes.previousValue;
    let isFirstChange = changes.firstChange;
  }
```


**<u>ngOnInit():</u>** This lifecycle hook called by Angular to indicate that Angular is done creating the component. We use this hook for all the initialization/declaration and avoid stuff to work in the constructor.
**Syntax:**
```javascript
  ngOnInit(): void {
    //this is the right place for all the initializations.
  }
```

**<u>ngDoCheck():</u>** This hook will detect or act upon those changes that Angular can't or won't detect on its own. The ngDoCheck() detects deep changes like a property change in object or item is pushed into array even without reference change. In more simpler terms.
```
It's generally a component check on following occasions.
  - Update child component input binding
  - Update DOM interpolation.
  - Update query list.

```

**Syntax:**
```javascript
  ngDoCheck(): void {
    //this is the where we write our logic whenever an application has to respond upon certain changes.
  }
```

**<u>ngAfterContentInit():</u>** This hook responds after Angular completes initialization of directive's content and after every default change detection. We can also define an ngAfterContentInit() method in our component to handle any additional initialization tasks. This hook gets called after components external content (content passed by ng-content directive) has been initialized.

**Syntax:**
```javascript
  ngAfterContentInit(): void {
  }
```

**<u>ngAfterContentChecked():</u>** It responds after Angular checks the content projected into the directive or component. This hook gets called after ngAfterContentInit() and every subsequent ngDoCheck(). It can be useful if you want to implement additional initialization tasks after Angular has fully initialized the component/directive's content.

**Syntax:**
```javascript
  ngAfterContentChecked(): void {
  //all extra initialization tasks can get implemented here.. 
}
```

**<u>ngAfterViewInit():</u>** This hooks respond after Angular initializes the component's views and child views, or the view that contains the directive. It is invoked only once when the view is instantiated. This is the best place where we can access our DOM nodes and perform any manipulation on them.

**Syntax:**
```javascript
  ngAfterViewInit(): void {
  }
```
**<u>ngAfterViewChecked():</u>** It respond after Angular checks the component's views and child views, or the view that contains the directive and get called after the ngAfterViewInit() and every subsequent ngAfterContentChecked().The ngAfterViewChecked() would be invoked once the DOM tree get any change. So if the DOM tree got change for many times, the ngAfterViewChecked() method would be invoked many times.

**Syntax:**
```javascript
  ngAfterViewChecked(): void {
  }
```

**<u>ngOnDestroy():</u>** This hook gets called immediately before Angular destroys the directive or component. So, all the cleanup functions like unsubscribing the observables and detach event handlers to avoid memory leaks can get implemented here. This hooks gets called only once per lifetime cycle.

**Syntax:**
```javascript
  ngOnDestroy(): void {
    //write all your cleanup logic here..
  }
```


🔥 Hopefully, this article has illustrated all the insight from Angular Lifecycle Hooks and if you find this article helpful then give it a love.❤