Complete Guide to Life Cycle of Angular Components Hooks (With Code)
By Rohan Vats
Updated on Apr 03, 2025 | 22 min read | 11.0k views
Share:
For working professionals
For fresh graduates
More
By Rohan Vats
Updated on Apr 03, 2025 | 22 min read | 11.0k views
Share:
Table of Contents
Angular remains a leading framework for building dynamic web applications, and its demand in the job market continues to grow. If you’re into web development, learning Angular can open up great career opportunities. One way to do this is to understand the life cycle of Angular components' hooks.
Angular hooks are a specific set of phases during a component’s lifecycle. They help you control how components behave, update, and clean up in an application. Hooks like ngOnInit, ngOnChanges, and ngOnDestroy let you handle changes seamlessly and avoid performance issues. Knowing when and how to use them can take your coding skills to the next level.
Companies value developers who understand when to fetch data and how to clean up resources, all skills directly tied to lifecycle hook expertise. In this guide, we will break down Angular component lifecycle hooks in a simple way. Whether you are just starting or want to sharpen your skills, this will help you build better Angular applications. Let’s get started!
Angular is a powerful framework for building dynamic web applications that rely heavily on components. These components aren't just static pieces of UI; they have a lifecycle, a series of stages from start to end. Exploring this lifecycle is necessary for any Angular developer who wants to write efficient and maintainable code. Let’s understand the Angular component lifecycle and why it matters.
Every Angular component has a lifecycle, a series of stages that mark its existence. This lifecycle encompasses everything from the component's creation and initialization to its rendering on the screen and eventual destruction. Angular provides hooks, called lifecycle hooks, that allow you to access these key moments and execute custom logic.
The life cycle of Angular components is crucial because it directly affects how your app performs and stays stable. It's about making sure everything runs smoothly from start to finish. Here are the key reasons why you should leverage the life cycle of Angular components hooks:
Additionally, using the life cycle of Angular components hooks for change detection and content projection, you can effectively manage communication and interaction between parent and child components.
Angular executes lifecycle hooks in a specific order, creating a predictable flow for managing your components. Knowing this order allows you to place your code for optimal results strategically. Here's a step-by-step breakdown:
Ready to elevate your tech skills? Discover upGrad’s Software Engineering Courses designed to equip you with in-demand skills for a successful career!
Angular components have a distinct lifecycle, moving through stages from initialization to destruction. These stages play an important role in effective component management. Lifecycle methods, also known as hook events, allow developers to tap into specific moments in a component's life. These Angular hooks provide control, enabling you to execute custom logic at various phases of the application.
Let's explore some important methods for the life cycle of Angular components and how you can utilize them to enhance your Angular applications:
The constructor() in Angular is the first method called when a component is instantiated. While it is not technically a lifecycle hook, it plays a vital role in initializing the component class and setting up its dependencies. Here’s a detailed explanation:
The constructor() is primarily used for injecting services and dependencies into the component. Angular's dependency injection system automatically provides instances of services that are required by the component.
It initializes class-level variables and sets up the basic structure of the component. However, it should not contain logic that depends on Angular bindings or the DOM, as these are not yet initialized.
import { Component } from '@angular/core';
import { DataService } from './data.service';
@Component({
selector: 'app-example',
template: '<p>{{ message }}</p>',
})
export class ExampleComponent {
message: string;
constructor(private dataService: DataService) {
console.log('Constructor called');
this.message = 'Component Initialized';
}
}
The ngOnChanges lifecycle hook is your go-to for responding to changes in a component's @Input() properties. This method triggers every time an input property's value changes, allowing you to react dynamically to new data. By implementing ngOnChanges, you can execute custom logic based on these changes, ensuring your component stays up-to-date and behaves as expected.
This example logs changes to @Input() properties whenever they are updated.
import { Component, Input, OnChanges, SimpleChanges } from '@angular/core';
@Component({
selector: 'app-example',
template: '<p>{{ data }}</p>',
})
export class ExampleComponent implements OnChanges {
@Input() data: string;
@Input() count: number;
ngOnChanges(changes: SimpleChanges) {
for (let prop in changes) {
console.log(`Property ${prop} changed:`);
console.log('Previous:', changes[prop].previousValue);
console.log('Current:', changes[prop].currentValue);
}
}
}
In this example, the ngOnChanges method iterates (repeat) through the changes object, logging the previous and current values of each changed property. This allows you to track how your input properties are evolving and react accordingly.
Want to build dynamic web applications with Angular 8 but not sure where to start? Get hands-on with upGrad’s Angular 8 Tutorial.
The ngOnInit lifecycle hook is triggered once after the ngOnChanges method is first called. It is the perfect place to perform initial setup tasks for your component, such as fetching data from an API (Application Programming Interface), initializing variables, or setting up subscriptions. Consider ngOnInit your component's "ready" signal, giving you the opportunity to prepare everything before the full component rendering.
This example shows how to log a message when the component initializes. It can be extended to fetch API data or set initial values.
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-sample',
template: '<p>Component Loaded</p>',
})
export class SampleComponent implements OnInit {
ngOnInit() {
console.log('Component Initialized');
// Fetch API data or initialize variables
}
}
In this simple example, ngOnInit logs a message to the console, indicating that the component has been initialized. You can replace this with more complex logic, such as making an API call or setting up a subscription.
Sometimes, Angular's built-in change detection might not catch every change in your component's data, especially when dealing with complex objects or external data sources. That's where ngDoCheck comes in. This lifecycle hook lets you implement your custom change detection logic, giving you complete control over when and how your component updates. You can use this to optimize performance by only triggering updates when necessary.
This example logs a message every time Angular performs a change detection cycle, which can be useful for debugging.
import { Component, DoCheck } from '@angular/core';
@Component({
selector: 'app-check',
template: '<p>Change Detection Running</p>',
})
export class CheckComponent implements DoCheck {
ngDoCheck() {
console.log('Change detection triggered');
// Custom logic for tracking changes
}
}
In this example, the ngDoCheck method is called every time Angular detects a change. You can add your custom logic inside this method to track specific changes and react accordingly. For instance, you might compare an object's current value with its previous value and update the component only if a difference is detected.
The ngAfterContentInit hook is called after Angular projects external content into the component. This means that any content placed within the component's <ng-content> tags has been processed and rendered. Use this hook to perform any initialization logic that depends on the projected content being available.
This example logs the text of the projected content after it is inserted.
import { Component, AfterContentInit, ContentChild, ElementRef } from '@angular/core';
@Component({
selector: 'app-content',
template: '<ng-content></ng-content>',
})
export class ContentComponent implements AfterContentInit {
@ContentChild('projectedContent') content: ElementRef;
ngAfterContentInit() {
console.log('Projected content:', this.content.nativeElement.textContent);
}
}
In this example, @ContentChild is used to inject a reference to an element with the template reference variable projectedContent from the projected content. The ngAfterContentInit hook then logs the text content of this element to the console, demonstrating how you can access and manipulate projected content within your component.
The ngAfterContentChecked hook is invoked after Angular checks the content projected into the component via <ng-content>. This hook is called after ngAfterContentInit, and every subsequent time the content is checked. You might use this hook to respond to changes in the projected content, ensuring that your component adapts dynamically to its inputs.
This example logs a message every time the projected content is checked.
import { Component, AfterContentChecked } from '@angular/core';
@Component({
selector: 'app-content-check',
template: '<ng-content></ng-content>',
})
export class ContentCheckComponent implements AfterContentChecked {
ngAfterContentChecked() {
console.log('Projected content checked');
}
}
In this example, ngAfterContentChecked logs a message to the console every time the projected content is checked. This can be useful for debugging in coding or for triggering other actions based on changes to the projected content.
Take your JavaScript skills to the next level with upGrad’s Advanced JavaScript course. Learn advanced web development techniques!
The ngAfterViewInit hook is called after Angular has fully initialized the component's view and its child views. This is the ideal place to access and manipulate the component's Document Object Model (DOM) elements, as they are guaranteed to be available at this stage. Use this hook to set up event listeners, initialize third-party libraries that interact with the DOM, or perform other view-related tasks.
This example demonstrates how to access an element within the component's template after the view is initialized.
import { Component, AfterViewInit, ViewChild, ElementRef } from '@angular/core';
@Component({
selector: 'app-view',
template: '<p #viewContent>View Content</p>',
})
export class ViewComponent implements AfterViewInit {
@ViewChild('viewContent') view: ElementRef;
ngAfterViewInit() {
console.log('View initialized:', this.view.nativeElement.textContent);
}
}
In this example, ngAfterViewInit accesses the viewContent paragraph element using the @ViewChild decorator. It then logs the text content of the element to the console, confirming that the view has been fully initialized.
The ngAfterViewChecked hook is triggered after Angular checks the component's view and the views of its child components. This hook ensures that any changes made to the view are reflected in the component. You might use this to perform custom view-related logic after Angular's change detection runs, allowing you to react to updates in your templates.
This example logs a message whenever the component's view is checked for updates.
import { Component, AfterViewChecked } from '@angular/core';
@Component({
selector: 'app-view-check',
template: '<p>View Component</p>',
})
export class ViewCheckComponent implements AfterViewChecked {
ngAfterViewChecked() {
console.log('View checked');
}
}
In the example above, ngAfterViewChecked logs a message to the console each time the view is checked. You could use this hook to adjust the size or position of an element based on its rendered dimensions.
The ngOnDestroy hook is called just before Angular destroys the component. It's your chance to clean up any resources the component is using to prevent memory leaks and maintain a smooth user experience. This is the ideal place to unsubscribe from observables, detach event listeners, and release any other resources held by the component.
This example shows how to clean up a subscription before the component is removed from the DOM.
import { Component, OnDestroy } from '@angular/core';
import { Subscription, interval } from 'rxjs';
@Component({
selector: 'app-destroy',
template: '<p>Destroy Example</p>',
})
export class DestroyComponent implements OnDestroy {
private intervalSubscription: Subscription;
constructor() {
this.intervalSubscription = interval(1000).subscribe((count) => {
console.log('Tick:', count);
});
}
ngOnDestroy() {
console.log('Component is being destroyed');
this.intervalSubscription.unsubscribe();
}
}
In this example, the component subscribes to an interval observable. In ngOnDestroy, it unsubscribes from the observable to prevent the interval from continuing to run after the component is destroyed, which would cause a memory leak.
Streamline your development process with upGrad’s DevOps courses. Learn automation and deployment techniques!
Angular provides TypeScript interfaces for each lifecycle hook, and implementing these interfaces offers significant benefits. They help ensure that your components adhere to the expected structure, promote code clarity, and prevent common errors. When you implement a lifecycle interface, you're essentially telling Angular, "This component will use this specific lifecycle hook," which helps the framework manage your component's behavior more effectively.
Let’s explore the benefits and implementation of Angular lifecycle interfaces:
Lifecycle interfaces enhance code maintainability and prevent missing method implementations, contributing to more robust and predictable Angular applications. Here are some advantages:
Using multiple interfaces, you can implement multiple lifecycle hooks in a single component. This consolidates your product lifecycle management logic in one place, allowing you to manage different aspects of the component’s lifecycle within the same class. This keeps your code organized and efficient.
Example Code: Using Multiple Lifecycle Interfaces
This example demonstrates how to implement OnInit and OnDestroy in a single component, handling both initialization tasks and cleanup operations.
import { Component, OnInit, OnDestroy } from '@angular/core';
@Component({
selector: 'app-multiple-hooks',
template: '<p>Multiple Lifecycle Hooks</p>',
})
export class MultipleHooksComponent implements OnInit, OnDestroy {
ngOnInit() {
console.log('Component initialized');
}
ngOnDestroy() {
console.log('Component destroyed');
}
}
Explanation:
Learn server-side development with upGrad’s Node.js for Beginners course. Perfect for building scalable applications!
To build robust Angular apps, it's crucial to use lifecycle methods effectively. By following best practices, you can optimize performance, manage resources wisely, and avoid common pitfalls. It ensures your applications are both efficient and maintainable.
Let’s explore some best practices to help you make the most of Angular lifecycle methods in your projects:
Lifecycle hooks like ngDoCheck offer fine-grained control but can introduce performance issues if not used properly. ngDoCheck is triggered on every change detection cycle, regardless of whether the component's inputs have actually changed. Overusing it can lead to unnecessary computations and slow down your application.
To mitigate this, carefully consider whether ngDoCheck is truly needed. If you're only concerned with changes to specific input properties, use OnChanges instead. For complex scenarios, explore techniques like memoization or ChangeDetectionStrategy to optimize performance and reduce the frequency of checks. Always profile your application to identify performance bottlenecks before implementing complex change detection logic.
Proper cleanup helps prevent memory leaks and keeps your application efficient. When a component is destroyed, it is useful to unsubscribe from any observables, event listeners, or other resources it holds. The ngOnDestroy lifecycle hook is the ideal place to perform these cleanup tasks.
Here are the key steps to follow:
Struggling to set up and run your Angular project? Check out upGrad’s How to Run the Angular Project blog for a clear, step-by-step explanation.
Are you ready to master Angular and excel in your career in web development? upGrad provides a structured path to gaining expertise in this powerful framework. You’ll learn from industry experts, build real-world projects, and receive comprehensive career support. Whether you’re a beginner or an experienced developer, upGrad’s programs are designed to help you succeed in the dynamic field of Angular development.
upGrad’s Exclusive Software Development Webinar for you –
SAAS Business – What is So Different?
upGrad’s certification programs bridge skill gaps and enhance employability. Gain hands-on experience and validate your expertise with industry-recognized credentials. These programs provide opportunities for a successful career in Angular development. Below are some relevant upGrad courses, along with the skills and learning outcomes they offer:
Courses |
Key Skills |
What You Learn |
Angular, React, Node.js |
|
|
Angular, Data Structures and Algorithms |
|
|
Angular, Spring Boot, AWS |
|
|
Core DevOps concepts, Automation, and more |
|
At upGrad, you’ll benefit from mentorship from industry experts and gain access to a vast alumni network, connecting you with professionals worldwide. Here’s how:
Transitioning into an Angular role requires more than just technical skills. upGrad offers career transition support to help you secure your dream job. Here’s how:
Angular component lifecycle hooks play a significant role in building dynamic and efficient applications. These hooks help your components function smoothly, update seamlessly, and release resources when no longer needed. Mastering Angular component lifecycle hooks elevates you from a casual developer to a framework expert.
Remember that choosing the right lifecycle hook for each task is crucial; API calls belong in ngOnInit, DOM manipulations in ngAfterViewInit, and cleanup operations in ngOnDestroy. Don’t stop here; try using this life cycle of Angular components in real projects. Keep exploring, experimenting, and refining your knowledge. The more you practice, the more confident you’ll become.
Now that you understand Angular lifecycle hooks, why not take the next step? Start building your Angular projects and apply what you’ve learned. Let’s create powerful and efficient web applications with upGrad courses!
Here’s a list of some other upGrad courses that can help you improve your web development skills:
Boost your career with our popular Software Engineering courses, offering hands-on training and expert guidance to turn you into a skilled software developer.
Master in-demand Software Development skills like coding, system design, DevOps, and agile methodologies to excel in today’s competitive tech industry.
Stay informed with our widely-read Software Development articles, covering everything from coding techniques to the latest advancements in software engineering.
Get Free Consultation
By submitting, I accept the T&C and
Privacy Policy
India’s #1 Tech University
Executive PG Certification in AI-Powered Full Stack Development
77%
seats filled
Top Resources