Angular LifeCycle Hooks With Practical Guide and Scenarios to Understand clearly
Published: 2023-03-06 18:29:51

This blog covers all **Angular LifeCycle Hook**s with Practice a guide of all lifecycle with an example to demonstrate the same in

**3 simple sections
1.Concept 
2.Practical 
3.Scenarios.**

**1.Concept**

There are total 8 LifeCycle Hooks in Angular

**1.ngOnChanges():** 

**Purpose:** Respond when Angular sets or resets data-bound input properties. The method receives a SimpleChanges object of current and previous property values.
**Timing:**  Called before ngOnInit() and whenever one or more data-bound input properties change.

**2.ngOnInit():**

**Purpose:** Initialize the directive or component 
**Timing:** Called once, after the first ngOnChanges()

**3.ngDoCheck():**

**Purpose:** Detect and act upon changes that Angular can't or won't detect on its own. 
**Timing:** Called immediately after ngOnChanges() on every change detection run, and immediately after ngOnInit() on the first run.

**4.ngAfterContentInit():**

**Purpose:** Respond after Angular projects external content into the component's view, or into the view that a directive is in.
**Timing:**  Called once after the first ngDoCheck().

**5.ngAfterContentChecked():**

**Purpose:** Respond after Angular checks the content projected into the directive or component.
**Timing:** Called after ngAfterContentInit() and every subsequent ngDoCheck().

**6.ngAfterViewInit():**

**Purpose:** Respond after Angular initializes the component's views and child views, or the view that contains the directive.
**Timing:** Called once after the first ngAfterContentChecked()


**7.ngAfterViewChecked():**

**Purpose:** Respond after Angular checks the component's views and child views, or the view that contains the directive.
**Timing:** Called after the ngAfterViewInit() and every subsequent ngAfterContentChecked().

**8.ngOnDestroy():**

**Purpose:** Cleanup just before Angular destroys the directive or component.
**Timing:** Called immediately before Angular destroys the directive or component.



**2.Practical**

**Step I: Create a new Angular Project**

ng new TestHook 

**Step II: Create a two child components**

ng g c child1/child1
ng g c child2/child2

**Step III: So here now you have a app.component.ts which is parent open and paste below code**

message variable carrying some default i.e 'hy' value will helps us understanding  ngAfterContentInit and ngAfterViewInit

myVal variable helps us in understanding ngOnChanges
```
@ViewChild(Child1Component) viewChild: Child1Component;
 myVal: any = 1;
 message="hy";
 constructor() { }
 fun(){
   this.myVal++;
 }
ngOnChanges() {
   this.log('onChanges');
 }

 ngOnInit() {
   this.log('onInit');
 }

 ngDoCheck() {
   this.log('doCheck');
 }

 ngAfterContentInit() {
   this.log('afterContentInit');
 }

 ngAfterContentChecked() {
   this.log('afterContentChecked ' + this.message );
 }

 ngAfterViewInit() {
   this.log('afterViewInit ' + this.message);
 }

 ngAfterViewChecked() {
   this.message=this.viewChild.message;
   this.log('afterViewChecked ' + this.message);
 }

 ngOnDestroy(){
   this.log('ng Destroy');
 }
 log(cycleHook) {
   console.log(`%c${this.constructor.name}` + `: %c${cycleHook}`, 'background: #0000FF; color: #FFFF;', 'background: #222; color: #bada55; font-size: 1.01rem')
 }
 showChild1=true;
 update(){
   this.showChild1 = !this.showChild1;
 }
```

**Step IV: In app.component.html call the child component**

```
<div style="background-color: blue;">
   <p>Parent Component</p>
<button  (click)='fun()'>ng onchange</button>
<button (click)="update()">check child 1 On Destroy </button>
<app-child1 *ngIf="showChild1" [change]="myVal">
</app-child1>
</div>
```


**Step V: Update Child1 Component child1.component.html**

```
<div style="margin: 50px; background-color: red;">
   <h3>child of appComponent(Parent)</h3>
<button (click)="update()">check child 2 On Destroy </button>

<div >
   <br>
    message : <input [(ngModel)]="message">
 </div>
<app-child2 *ngIf="showChild2">
</app-child2>
</div>
```

**Step VI: Update Child1 Component child1.component.ts**

```
@Input() change = 1;
propChanges:any;
message="hy"
 constructor() { }
ngOnChanges(changes: SimpleChanges) {
 this.propChanges = changes;
 // console.log(this.propChanges);
   this.log('onChanges');
   this.log('onChanges:CurrVal::  '+this.propChanges.change.currentValue);
   this.log('onChanges:PreVal::  '+this.propChanges.change.previousValue);
   this.log('onChanges:changedORnot::  '+this.propChanges.change.firstChange);
 }
 ngOnInit() {
   this.log('onInit');
 }
 ngDoCheck() {
   this.log('doCheck');
 }

 ngAfterContentInit() {
   this.log('afterContentInit');
 }

 ngAfterContentChecked() {
   this.log('afterContentChecked ' + this.message);
 }

 ngAfterViewInit() {
   this.log('afterViewInit');
 }

 ngAfterViewChecked() {
   this.log('afterViewChecked ' + this.message);
 }

 log(cycleHook) {
   console.log(`%c${this.constructor.name}` + `: %c${cycleHook}`, 'background: #FF0000; color: #FFFF;', 'background: #222; color: #bada55; font-size: 1.01rem')
 }
 ngOnDestroy(){
   this.log('ng Destroy');
 }
 showChild2=true;
 update(){
   this.showChild2 = !this.showChild2;
 }
```

**Step VII: Update child2 Component child2.component.html**

```
<p>child2  works!</p>
```

**Step VIII: Update child2 Component child2.component.ts**

```

ngOnChanges() {
   this.log('onChanges');
 }

 ngOnInit() {
   this.log('onInit');
 }

 ngDoCheck() {
   this.log('doCheck');
 }

 ngAfterContentInit() {
   this.log('afterContentInit');
 }

 ngAfterContentChecked() {
   this.log('afterContentChecked');
 }

 ngAfterViewInit() {
   this.log('afterViewInit');
 }

 ngAfterViewChecked() {
   this.log('afterViewChecked');
 }

 log(cycleHook) {
   console.log(`%c${this.constructor.name}` + `: %c${cycleHook}`, 'background: #00FF00; color: #FFFF;', 'background: #222; color: #bada55; font-size: 1.01rem')
 }
 ngOnDestroy(){
   this.log('ng Destroy');
 }
```


**Step IX: Run the project and observe life cycle hooks execution in console**

ng serve



**3.Scenarios**

**1.Initial execution Flow**


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/oj3ws3rrrfudqwnyi9is.png)


**2.After ngOnchanges()** 

click on button with label "ng onchange" and observe current value and previous value changes in the console related to ngOnChanges.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4td6setbu5v5mry69tbz.png)

**3.ngOnDestroy()** 

click on buttons with label "check child1 On Destroy" or  "check child2 On Destroy" to observe ngOnDestroy hook.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xl4p1ecnva02e0nv2087.png)


**4.Difference between afterContentChecked and afterViewChecked**

Try to add the text to the initialized text in the input box to observe afterContentChecked and afterViewChecked


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7nb1vo4ijhneaw3a201q.png)