We use cookies to enhance your experience on the site
CodeWorlds

Lifecycle Hooks - Warrior Rituals

Every Angular component goes through a specific lifecycle - from birth to death. Lifecycle hooks allow you to react to these moments.

Main Lifecycle Hooks

1import {
2  Component,
3  OnInit,
4  OnDestroy,
5  OnChanges,
6  SimpleChanges,
7  AfterViewInit
8} from '@angular/core';
9
10@Component({
11  selector: 'app-samurai',
12  template: \`<p>{{ name }}</p>\`
13})
14export class SamuraiComponent implements OnInit, OnDestroy, OnChanges, AfterViewInit {
15  @Input() name = '';
16
17  // 1. Called on every @Input change
18  ngOnChanges(changes: SimpleChanges): void {
19    console.log('Data changed:', changes);
20  }
21
22  // 2. Called once after the first ngOnChanges
23  ngOnInit(): void {
24    console.log('Component initialized');
25    // Ideal place for fetching data from API
26  }
27
28  // 3. Called after the view is initialized
29  ngAfterViewInit(): void {
30    console.log('View ready');
31    // Access to DOM elements via ViewChild
32  }
33
34  // 4. Called before the component is destroyed
35  ngOnDestroy(): void {
36    console.log('Component being destroyed');
37    // Cleanup: cancel subscriptions, timers
38  }
39}

Order of Calls

  1. constructor - creating the instance
  2. ngOnChanges - @Input change (can happen multiple times)
  3. ngOnInit - initialization (once)
  4. ngDoCheck - custom change detection
  5. ngAfterContentInit - after ng-content initialization
  6. ngAfterContentChecked - after ng-content check
  7. ngAfterViewInit - after view initialization
  8. ngAfterViewChecked - after view check
  9. ngOnDestroy - before destruction

Practical Example

1@Component({
2  selector: 'app-timer',
3  standalone: true,
4  template: \`<p>Time: {{ seconds }}s</p>\`
5})
6export class TimerComponent implements OnInit, OnDestroy {
7  seconds = 0;
8  private intervalId?: number;
9
10  ngOnInit(): void {
11    this.intervalId = window.setInterval(() => {
12      this.seconds++;
13    }, 1000);
14  }
15
16  ngOnDestroy(): void {
17    // Important! We clear the interval on destruction
18    if (this.intervalId) {
19      clearInterval(this.intervalId);
20    }
21  }
22}
Go to CodeWorlds