0
0
Angularframework~5 mins

Lifecycle execution order mental model in Angular

Choose your learning style9 modes available
Introduction

Understanding the order of lifecycle events helps you control what happens when your Angular component starts, updates, or ends.

You want to run code right after a component appears on the screen.
You need to respond when input data to a component changes.
You want to clean up resources before a component disappears.
You want to track when Angular checks your component for changes.
You want to initialize child components or templates after they load.
Syntax
Angular
ngOnChanges(changes: SimpleChanges) {}
ngOnInit() {}
ngDoCheck() {}
ngAfterContentInit() {}
ngAfterContentChecked() {}
ngAfterViewInit() {}
ngAfterViewChecked() {}
ngOnDestroy() {}

Each method is called automatically by Angular at a specific time.

You only implement the methods you need in your component class.

Examples
This runs once after the component is created and inputs are set.
Angular
ngOnInit() {
  console.log('Component initialized');
}
This runs whenever input properties change, even before ngOnInit.
Angular
ngOnChanges(changes: SimpleChanges) {
  console.log('Input changed', changes);
}
This runs just before Angular removes the component, good for cleanup.
Angular
ngOnDestroy() {
  console.log('Component is about to be removed');
}
Sample Program

This component shows how Angular calls lifecycle methods in order. When the input data changes, ngOnChanges runs first and updates the message. Then ngOnInit runs once after the first change. When the component is removed, ngOnDestroy runs to clean up.

Angular
import { Component, Input, OnChanges, OnInit, OnDestroy, SimpleChanges } from '@angular/core';

@Component({
  selector: 'app-lifecycle-demo',
  template: `<p>{{message}}</p>`
})
export class LifecycleDemoComponent implements OnChanges, OnInit, OnDestroy {
  @Input() data = '';
  message = '';

  ngOnChanges(changes: SimpleChanges) {
    this.message = `Input changed to: ${this.data}`;
    console.log('ngOnChanges called');
  }

  ngOnInit() {
    console.log('ngOnInit called');
  }

  ngOnDestroy() {
    console.log('ngOnDestroy called');
  }
}
OutputSuccess
Important Notes

ngOnChanges runs before ngOnInit and every time input changes.

ngOnInit runs once after the first ngOnChanges.

ngOnDestroy is your chance to clean up like stopping timers or unsubscribing.

Summary

Angular calls lifecycle methods in a specific order to manage your component.

ngOnChanges runs first on input changes, then ngOnInit runs once.

Use ngOnDestroy to clean up before the component is removed.