Component Lifecycle in Angular
Angular lifecycle hooks are methods that allow developers to tap into key moments of an Angular component’s life cycle, from its creation to its destruction which includes initialization, changes, and destruction. The most commonly used lifecycle hooks are:
- Constructor: Called when page loads at first time. Called only one time.
- ngOnChanges: Execute multiple times. first time will execute when component created/loaded. When there is change in custom property with @input decorator that every time this hook will called. worked with argument - simple changes
- ngOnInit: Called once the component is initialized. Ideal for setting up the component’s state.
- ngDoCheck: Used to detect changes manually (called with each change detection cycle).
- ngAfterContentInit: Called after the content is projected into the component.
- ngAfterContentChecked: Called after the projected content is checked.
- ngAfterViewInit: Called after the view has been initialized.
- ngAfterViewChecked: Called after Angular checks the component’s view.
- ngOnDestroy: Called just before the component is destroyed. Use it to clean up resources, like unsubscribing from observables.
Before dive in, lets create prerequisite project:
We will need parent and child component. We will have Input field in parent component and will pass that inputed value to the child and will show in child component.
parent.component.ts
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-parent', templateUrl: './parent.component.html', styleUrls: ['./parent.component.css'] }) export class ParentComponent implements OnInit { constructor() { } ngOnInit(): void { } value:string = ''; SubmitValue(val: any) { this.value = val.value; } }
parent.component.html
<h1>Lifecycle Hooks</h1> <input type="text" placeholder="Input here..." #val> <button (click)="SubmitValue(val)">Submit Value</button> <br><br> <app-child [inputValue]="value"></app-child>
child.component.ts
import { Component, Input, OnInit } from '@angular/core'; @Component({ selector: 'app-child', templateUrl: './child.component.html', styleUrls: ['./child.component.css'] }) export class ChildComponent implements OnInit { constructor() { } @Input() inputValue: string = "LifeCycle Hooks"; ngOnInit(): void { } }
child.component.html
<div> Input Value: <strong>{{inputValue}}</strong> </div>
We will have output like this:
1.Constructor
- The constructor is a TypeScript class method used to initialize a component. It is called before any Angular lifecycle hooks.
- Primary use: Initialize dependency injection and set up variables.
export class ChildComponent implements OnInit { constructor() { **console.log("Constructor Called");** } @Input() inputValue: string = "LifeCycle Hooks"; ngOnInit(): void {} }
2.ngOnChanges
- Invoked when any input properties of a component are changed.
- Provides a SimpleChanges object containing the previous and current values of the input properties.
- Usage: Update the data input property from the parent component to trigger this hook.
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-parent', templateUrl: './parent.component.html', styleUrls: ['./parent.component.css'] }) export class ParentComponent implements OnInit { constructor() { } ngOnInit(): void { } value:string = ''; SubmitValue(val: any) { this.value = val.value; } }
Again I have inputed the value and again ngOnChanges called but constructor only called once.
Let's see what we have in changes argument:
<h1>Lifecycle Hooks</h1> <input type="text" placeholder="Input here..." #val> <button (click)="SubmitValue(val)">Submit Value</button> <br><br> <app-child [inputValue]="value"></app-child>
Let's put some value and see:
3.ngOnInit
- Called once after the first ngOnChanges.
- Primary use: Initialize the component and set up any necessary data for rendering.
import { Component, Input, OnInit } from '@angular/core'; @Component({ selector: 'app-child', templateUrl: './child.component.html', styleUrls: ['./child.component.css'] }) export class ChildComponent implements OnInit { constructor() { } @Input() inputValue: string = "LifeCycle Hooks"; ngOnInit(): void { } }
4.ngDoCheck
- Runs every time Angular detects a change in the component or its children.
- Use this for custom change detection logic.
<div> Input Value: <strong>{{inputValue}}</strong> </div>
5.ngAfterContentInit
- Called once after content (e.g.,
) is projected into the component.
child.component.html
export class ChildComponent implements OnInit { constructor() { **console.log("Constructor Called");** } @Input() inputValue: string = "LifeCycle Hooks"; ngOnInit(): void {} }
parent.component.html
export class ChildComponent implements OnInit, OnChanges { constructor() { console.log("Constructor Called"); } ngOnChanges(changes: SimpleChanges): void { console.log("ngOnChanges Called"); } @Input() inputValue: string = "LifeCycle Hooks"; ngOnInit(): void {} }
child.component.ts
ngOnChanges(changes: SimpleChanges): void { console.log("ngOnChanges Called", changes); }
6.ngAfterContentChecked
- Called after every check of the projected content.
- Use sparingly to avoid performance issues.
export class ChildComponent implements OnInit, OnChanges { constructor() { console.log("Constructor Called"); } ngOnChanges(changes: SimpleChanges): void { console.log("ngOnChanges Called"); } @Input() inputValue: string = "LifeCycle Hooks"; ngOnInit(): void { console.log("ngOnInit Called"); } }
let's play around this:
export class ChildComponent implements OnInit, OnChanges, DoCheck { constructor() { console.log("Constructor Called"); } ngOnChanges(changes: SimpleChanges): void { console.log("ngOnChanges Called", changes); } @Input() inputValue: string = "LifeCycle Hooks"; ngOnInit(): void { console.log("ngOnInit Called"); } ngDoCheck() { console.log("ngDoCheck Called"); } }
When there is change in ng-content again ngAfterContentChecked called.
7.ngAfterViewInit
- Called once after the component's view and its child views have been initialized.
- Useful for initializing third-party libraries or DOM manipulations.
8.ngAfterViewChecked
- Invoked after every check of the component's view and its child views.
9.ngOnDestroy
- Called just before the component is destroyed.
- Use it for cleanup tasks like unsubscribing from Observables or detaching event listeners.
ngOnDestroy will only called when we destroy any component, so let's try to remove child component when we click Destroy component button.
Let's make arrangements:
parent.component.ts
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-parent', templateUrl: './parent.component.html', styleUrls: ['./parent.component.css'] }) export class ParentComponent implements OnInit { constructor() { } ngOnInit(): void { } value:string = ''; SubmitValue(val: any) { this.value = val.value; } }
parent.component.html
<h1>Lifecycle Hooks</h1> <input type="text" placeholder="Input here..." #val> <button (click)="SubmitValue(val)">Submit Value</button> <br><br> <app-child [inputValue]="value"></app-child>
Before we click the Destroy component button:
After we click the Destroy component button:
Lifecycle Hook Sequence:
- Constructor
- ngOnChanges (if @Input properties exist)
- ngOnInit
- ngDoCheck
- ngAfterContentInit
- ngAfterContentChecked
- ngAfterViewInit
- ngAfterViewChecked
- ngOnDestroy
By understanding and using these hooks effectively, you can manage the component's behavior at different stages of its lifecycle.
The above is the detailed content of Component Lifecycle in Angular. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...
