Every Angular component goes through a specific lifecycle - from birth to death. Lifecycle hooks allow you to react to these moments.
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}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}