Disqus Shortname

Responsive Advertisement

Angular the series Part 10: Component Lifecycle

    Angular provides a structured component lifecycle that determines how a component is created, updated, and destroyed. Each stage in this lifecycle has lifecycle hooks that developers can use to control component behavior at critical moments.
    In this article, we'll explore all Angular component lifecycle hooks, their purpose, and how to use them with examples.


What is the Angular Component Lifecycle?

    The Angular component lifecycle defines the stages a component goes through, from initialization to destruction. These stages allow Angular to manage the component’s rendering, data binding, and change detection.
Each phase of the lifecycle is associated with lifecycle hooks, which are methods that Angular automatically calls at specific moments.


All Angular Lifecycle Hooks

Angular provides eight lifecycle hooks, which are grouped based on their execution phase:
 

Creation Phase (Component is initialized)

  • ngOnChanges()
  • ngOnInit()

Change Detection Phase (Component updates occur)

  • ngDoCheck()
  • ngAfterContentInit()
  • ngAfterContentChecked()
  • ngAfterViewInit()
  • ngAfterViewChecked()

Destruction Phase (Component is removed)

  • ngOnDestroy()

1. ngOnChanges()

When does it run?
  • Runs before ngOnInit()
  • Executes whenever an @Input() property changes
Use case
  • Responding to changes in parent-component-bound properties
Example
import { Component, Input, OnChanges, SimpleChanges } from '@angular/core';

@Component({
 selector: 'app-child',
 template: `<p>Message: {{message}}</p>`
})
export class ChildComponent implements OnChanges {
 @Input() message: string;

 ngOnChanges(changes: SimpleChanges): void {
 console.log('Message changed:', changes.message.currentValue);
 }
}

2. ngOnInit()

When does it run?
  • Runs once, after ngOnChanges()
  • Executes after input properties are set
Use case
  • Initializing component state
  • Fetching data from an API
Example
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-example',
  template: `<p>Component Initialized</p>`
})
export class ExampleComponent implements OnInit {
  ngOnInit(): void {
    console.log('Component Initialized');
  }
}

3. ngDoCheck()

When does it run?
  • Runs after ngOnChanges() and ngOnInit()
  • Executes on every change detection cycle
Use case
  • Detecting changes in objects or arrays that Angular doesn’t track automatically
Example
import { Component, DoCheck } from '@angular/core';
@Component({
  selector: 'app-check',
  template: `

Change Detection Running...

` }) export class CheckComponent implements DoCheck { ngDoCheck(): void { console.log('Change detection triggered'); } }

4. ngAfterContentInit()

When does it run?
  • Runs once
  • Executes after content projection (<ng-content>) has been inserted
Use case
  • Performing operations on projected content
Example
import { Component, AfterContentInit, ContentChild, ElementRef } from '@angular/core';
@Component({
  selector: 'app-content-child',
  template: ``
})

export class ContentChildComponent implements AfterContentInit {
  @ContentChild('content') content: ElementRef;
  
  ngAfterContentInit(): void {
    console.log('Projected content:', this.content.nativeElement.innerText);
  }
}

5. ngAfterContentChecked()

When does it run?
  • Runs after ngAfterContentInit()
  • Executes every time change detection runs
Use case
  • Reacting to changes in projected content
Example
import { Component, AfterContentChecked } from '@angular/core';

@Component({
  selector: 'app-content-check',
  template: `<p>Projected Content Check</p>`
})
export class ContentCheckComponent implements AfterContentChecked {
  ngAfterContentChecked(): void {
    console.log('Projected content checked');
  }
}

6. ngAfterViewInit()

When does it run?
  • Runs once
  • Executes after the component’s view and child views are initialized
Use case
  • Accessing and modifying the DOM or child components
Example
import { Component, AfterViewInit, ViewChild, ElementRef } from '@angular/core';

@Component({
  selector: 'app-view-init',
  template: `<p #para>View Initialized</p>`
})
export class ViewInitComponent implements AfterViewInit {
  @ViewChild('para') paragraph: ElementRef;

  ngAfterViewInit(): void {
    console.log('View initialized:', this.paragraph.nativeElement.innerText);
  }
}

7. ngAfterViewChecked()

When does it run?
  • Runs after ngAfterViewInit()
  • Executes every time change detection runs
Use case
  • Handling updates in the component’s view
Example
import { Component, AfterViewChecked } from '@angular/core';

@Component({
  selector: 'app-view-check',
  template: `<p>View Checked</p>`
})
export class ViewCheckComponent implements AfterViewChecked {
  ngAfterViewChecked(): void {
    console.log('View checked');
  }
}

8. ngOnDestroy()

When does it run?
  • Executes before the component is removed from the DOM
Use case
  • Cleaning up resources, such as unsubscribing from observables or removing event listeners
Example
import { Component, OnDestroy } from '@angular/core';

@Component({
  selector: 'app-destroy',
  template: `<p>Component will be destroyed</p>`
})
export class DestroyComponent implements OnDestroy {
  ngOnDestroy(): void {
    console.log('Component destroyed');
  }
}


Summary of Lifecycle Hooks

Hook When it Runs
ngOnChanges() When @Input() values change Respond to parent changes
ngOnInit() After component initialization Initialize state, fetch data
ngDoCheck() On every change detection cycle Custom change detection
ngAfterContentInit() After content projection Access projected content
ngAfterContentChecked() After content is checked Monitor projected content
ngAfterViewInit() After component view initializes Manipulate the DOM
ngAfterViewChecked() After view is checked Perform final UI updates
ngOnDestroy() Before component is destroyed Clean up resources

Conclusion

    Understanding Angular’s lifecycle hooks allows developers to write efficient, maintainable, and optimized components. By using the right hooks at the right time, you can improve performance, manage resources, and handle changes effectively.