Ad Code

✨🎆 JOIN MERN, JAVA, PYTHON, AI, DEVOPS, SALESFORCE Courses 🎆✨

Get 100% Placement Oriented Program CLICK to new more info click

Angular Life Cycle Hooks

 When Angular creates a component, it goes through different stages. These stages are called Lifecycle Hooks.


Angular Component → Created → Initialized → Updated → Destroyed

🔹 Important Lifecycle Hooks (Most Important for Students)

Hook When It Runs Purpose

ngOnChanges() When input value changes Detect input changes

ngOnInit() After component created Initialize data

ngDoCheck() During every change detection Custom change logic

ngAfterViewInit() After view loads Access DOM

ngOnDestroy() Before component removed Cleanup


Simple Example:


ng generate component lifecycle-demo

import { Component, OnInit, OnChanges, DoCheck, AfterViewInit, OnDestroy, Input, SimpleChanges } from '@angular/core';


@Component({

  selector: 'app-lifecycle-demo',

  templateUrl: './lifecycle-demo.component.html'

})

export class LifecycleDemoComponent implements OnInit, OnChanges, DoCheck, AfterViewInit, OnDestroy {


  @Input() message: string = '';


  constructor() {

    console.log("1. Constructor called");

  }


  ngOnChanges(changes: SimpleChanges) {

    console.log("2. ngOnChanges called", changes);

  }


  ngOnInit() {

    console.log("3. ngOnInit called");

  }


  ngDoCheck() {

    console.log("4. ngDoCheck called");

  }


  ngAfterViewInit() {

    console.log("5. ngAfterViewInit called");

  }


  ngOnDestroy() {

    console.log("6. ngOnDestroy called");

  }

}


Create this code on parent component means create another component

HTML Page

<button (click)="changeMessage()">Change Message</button>

<app-lifecycle-demo [message]="parentMessage"></app-lifecycle-demo>


.ts file

parentMessage = "Hello Students";

changeMessage() {
this.parentMessage = "Message Changed!";
}


When app runs:

Constructor
ngOnChanges
ngOnInit
ngDoCheck
ngAfterViewInit

When button clicked:

ngOnChanges
ngDoCheck


When component removed:
ngOnDestroy





Post a Comment

0 Comments