Angular Component Lifecycle Hooks Explained

Angular Component Lifecycle Hooks Explained

19 Jul 2025
Advanced
52.5K Views
9 min read
Learn with an interactive course and practical hands-on labs

Angular Course Free with Certificate - Beginner Level

Angular Lifecycle Hooks are essential tools for building responsive, dynamic web apps. If you're working with Angular components, understanding these hooks—like ngOnInit, ngOnDestroy, and others—is crucial to writing optimized, maintainable code. In this guide, you'll explore each Angular lifecycle method with practical examples. Let us now dive into an insightful Angular tutorial and discuss Angular Component Lifecycle Hooks, Stages of Angular Component Lifecycle, eight lifecycle hooks, and why we need Angular lifecycle hooks.

What are Angular Lifecycle Hooks?

Lifecycle hooks are Angular methods that are executed at certain points during a component's lifecycle. These methods allow you to tap into the Angular component lifecycle and apply custom logic or operations at specified points in time. Angular lifecycle hooks give you precise control over your component’s behavior at different stages of its existence.
Angular Lifecycle hooks diagram

Angular Component Lifecycle Stages

Each Angular component goes through a series of lifecycle stages, and Angular provides hooks you can implement to execute logic at each one. Here's a brief, explanation of each Angular lifecycle phase.

1. Creation Phase

  • Angular instantiates the component class and initializes input properties.
  • constructor() sets up dependencies.
  • ngOnChanges() responds to input changes.
  • ngOnInit() is ideal for data fetching and one-time setup.

2. Change Detection & View Rendering Phase

  • Angular checks for changes and updates the DOM accordingly.
  • Hooks like ngDoCheck() let you add custom detection logic.
  • Content and view hooks (ngAfterContentInit(), ngAfterViewInit(), etc.) trigger when rendering completes.

 3. Destruction Phase

  • Called just before the component is removed from the DOM.
  • ngOnDestroy() is used for cleanup tasks like unsubscribing and removing listeners.
  • Skipping this can lead to memory leaks and performance issues.

8 Lifecycle Hooks in Angular (with Code Examples)

Angular has many lifecycle hooks that allow you to inject code at precise times in a component's or directive's life cycle. These hooks function similarly to checkpoints, allowing you to conduct specified tasks based on the current state of the component. In Angular, there are eight lifecycle hooks:

angular lifecyle hooks

  1. ngOnChanges
  2. ngOnInit
  3. ngDoCheck
  4. ngAfterContentInit
  5. ngAfterContentChecked
  6. ngAfterViewInit
  7. ngAfterViewChecked
  8. ngOnDestroy

1. ngOnChanges

When the value of an input binding to the component changes, this hook is called.

Example of ngOnChanges

ngOnChanges(changes: SimpleChanges) {
 if (changes['data']) {
  this.processData(changes['data'].currentValue);
 }
}
This example determines whether or not the data input binding has changed. If it has, it uses the new data value to run the processData method.

2. ngOnInit

Once the component has been initialized and its input bindings have been handled, this hook is invoked.

Example of ngOnInit

ngOnInit() {
 this.initialData = this.getData();
}
After the component has been properly initialized, this example retrieves initial data from the getData function and stores it in the initialData property.

3. ngDoCheck

Every change detection cycle ends with a call to this hook. Because of the performance ramifications, it is frequently regarded as an anti-pattern.

Example of ngDoCheck

ngDoCheck() { if (this.element.clientWidth !== this.lastWidth) {  this.adjustLayout();  this.lastWidth = this.element.clientWidth; }}
This example checks to see if the width of the element has changed. If so, the layout is adjusted and the lastWidth attribute is updated. This is not advised due to potential performance difficulties.

4. ngAfterContentInit

After the projected content (content projected into the component with <ng-content>) has been initialized, this hook is invoked.

Example of ngAfterContentInit

ngAfterContentInit() { this.content = this.contentElement.nativeElement.textContent;}
This example uses contentElement to retrieve the content projected into the component and store it in its content property.

5. ngAfterContentChecked

This hook is invoked at the end of each change detection cycle for the projected content.

Example of ngAfterContentChecked

ngAfterContentChecked() { if (this.content) {  this.analyzeContent(this.content); }}
This example checks whether or not planned content exists as well as if so, analyses it.

6. ngAfterViewInit

After the component's view (including its children) has been fully initialized, this hook is called.

Example of ngAfterViewInit

ngAfterViewInit() { this.canvas = this.canvasElement.nativeElement; this.drawChart(this.data);}
This example retrieves the canvas element & utilizes it to create a chart using the data provided.

7. ngAfterViewChecked

This hook is invoked at the end of each change detection cycle for the component's view.

Example of ngAfterViewChecked

ngAfterViewChecked() { if (this.isScrolling) {  this.updateScrollPosition(); }}
This example determines whether the component is actively scrolling and, if so, adjusts the scroll position.

8. ngOnDestroy

When the component is destroyed, this hook is called.

Example of ngOnDestroy

ngOnDestroy() { this.unsubscribeFromEvents();}
To prevent memory leaks, this example unsubscribes from any event subscriptions.

Angular Lifecycle Hooks Summary Table

Lifecycle HookCalled WhenTechnical Purpose
ngOnChanges()On input property changeRespond to changes in @Input() bindings using SimpleChanges
ngOnInit()Once after first ngOnChangesInitialize data, fetch from APIs, setup default states
ngDoCheck()On every change detection runCustom change detection logic
ngAfterContentInit()After content projected via <ng-content> is initializedInteract with projected content
ngAfterContentChecked()After each check of projected contentPerform post-check operations
ngAfterViewInit()After component’s view (and child views) initializedAccess ViewChild or ViewChildren, manipulate DOM
ngAfterViewChecked()After every check of the viewReact to changes in the view or child views
ngOnDestroy()Before component is destroyedUnsubscribe from observables, clear intervals, avoid memory leaks

Why Are Angular Lifecycle Hooks Important?

Angular components go through different stages — like being created, shown, updated, and destroyed. Angular lifecycle hooks are essential for managing the behavior of components and directives at various stages of their existence. Lifecycle hooks let you run code at each of these moments.

ReasonWhat Hook Helps 
Run logic after creationngOnInit()
Respond to input changesngOnChanges()
Customize change detectionngDoCheck()
Work with content projectionngAfterContentInit()
Work with the view/DOMngAfterViewInit()
Cleanup to prevent leaksngOnDestroy()
Summary

Component creation, update, & destruction all involve angular magic.Angular Lifecycle hooks enable checkpoints for injecting code at certain stages in the app's lifecycle, improving app functionality and speed. Make good use of these hooks for a smooth and efficient Angular experience.

FAQs

Angular uses various change detection processes to track changes in data-bound attributes throughout the lifecycle. An Angular lifecycle begins when an Angular component class is initiated. It then defines the view of the component as well as the view of the child components.

OnInit. OnInit is a lifecycle hook that is called when Angular has initialized all of a directive's data-bound properties. To handle any additional initialization chores, define a ngOnInit() function. When the component's first change detection is run, this hook is called.

As it produces, updates, and destroys directives and components, Angular calls lifecycle hook methods on them. Angular manages the lifespan of a component. It is created, and rendered, its descendants are created and rendered, it is checked when its data-bound properties change, and it is destroyed before being removed from the DOM.

A lifecycle hook allows the instance to wait for a given amount of time (one hour by default) for the action to complete before transitioning to the next state.

Take our Angular skill challenge to evaluate yourself!

In less than 5 minutes, with our skill challenge, you can identify your knowledge gaps and strengths in a given skill.

GET FREE CHALLENGE

Share Article
About Author
Nishu Goel (Angular developer, Author, and Speaker)

Nishu is an Angular developer, Author, and Speaker. She is working as a Developer at IBM with her major interest in technologies and frameworks like Angular, JavaScript, CSS. She also works towards achieving the SDGs by United Nations, by applying technology towards better livelihood. Her hobbies include blogging about the latest technologies and creating a better ecosystem for students.
Live Training - Book Free Demo
ASP.NET Core Certification Training
26 Jul
07:00AM - 09:00AM IST
Checkmark Icon
Get Job-Ready
Certification
Advanced Full-Stack .NET Developer with Gen AI Certification Training
26 Jul
07:00AM - 09:00AM IST
Checkmark Icon
Get Job-Ready
Certification
.NET Microservices Certification Training
27 Jul
07:00AM - 09:00AM IST
Checkmark Icon
Get Job-Ready
Certification
ASP.NET Core Project
27 Jul
08:30PM - 10:30PM IST
Checkmark Icon
Get Job-Ready
Certification
.NET Solution Architect Certification Training
27 Jul
07:00AM - 09:00AM IST
Checkmark Icon
Get Job-Ready
Certification
Accept cookies & close this