Understanding the component lifecycle helps you know when and how your Angular component starts, updates, and ends. This lets you run code at the right time to make your app work smoothly.
0
0
Component lifecycle overview in Angular
Introduction
You want to run code when a component first appears on the screen.
You need to update something when input data changes.
You want to clean up resources when a component is removed.
You want to react to changes in the component's view or content.
You want to perform actions after Angular has checked the component's data.
Syntax
Angular
import { Component, OnInit, OnChanges, OnDestroy, AfterViewInit, AfterContentInit } from '@angular/core'; @Component({ selector: 'app-example', template: `<p>Example works!</p>`, standalone: true }) export class ExampleComponent implements OnInit, OnChanges, AfterViewInit, AfterContentInit, OnDestroy { ngOnChanges() { // Called when input properties change } ngOnInit() { // Called once after first ngOnChanges } ngAfterContentInit() { // Called after content (ng-content) is projected } ngAfterViewInit() { // Called after component's view is initialized } ngOnDestroy() { // Called just before component is destroyed } }
Each lifecycle method runs at a specific time during the component's life.
Implement only the lifecycle hooks you need for your component.
Examples
Runs code once when the component is ready.
Angular
export class MyComponent implements OnInit { ngOnInit() { console.log('Component initialized'); } }
Runs code whenever input properties change.
Angular
export class MyComponent implements OnChanges { ngOnChanges() { console.log('Input changed'); } }
Runs cleanup code when the component is removed.
Angular
export class MyComponent implements OnDestroy { ngOnDestroy() { console.log('Component destroyed'); } }
Sample Program
This component logs messages when it initializes, when its input changes, and when it is destroyed. It shows how lifecycle hooks help track component events.
Angular
import { Component, Input, OnInit, OnChanges, OnDestroy, SimpleChanges } from '@angular/core'; @Component({ selector: 'app-lifecycle-demo', template: `<p>Message: {{message}}</p>`, standalone: true }) export class LifecycleDemoComponent implements OnInit, OnChanges, OnDestroy { @Input() message = ''; ngOnChanges(changes: SimpleChanges) { console.log('ngOnChanges called:', changes); } ngOnInit() { console.log('ngOnInit called'); } ngOnDestroy() { console.log('ngOnDestroy called'); } }
OutputSuccess
Important Notes
ngOnChanges runs before ngOnInit and whenever input properties change.
ngOnDestroy is useful to stop timers or unsubscribe from data streams.
Not all lifecycle hooks are needed in every component.
Summary
Angular components have special methods called lifecycle hooks.
These hooks run at key moments like creation, update, and destruction.
Use lifecycle hooks to run your code at the right time in the component's life.