Back to course

Component Lifecycle Hooks (OnInit, OnDestroy)

The Complete Angular Developer: From Zero to Hero

9. Component Lifecycle Hooks

Components go through a lifecycle: Angular creates them, renders them, checks when their data-bound properties change, and finally destroys them before removing them from the DOM. Angular provides hooks (interface methods) you can implement to tap into these key moments.

The Most Common Hooks

HookInterfaceTiming
ngOnInitOnInitCalled once, after the component is initialized and data-bound properties are set. Ideal for data fetching.
ngOnDestroyOnDestroyCalled once, just before Angular destroys the component. Ideal for cleanup (unsubscribing, clearing intervals).
ngDoCheckDoCheckCalled during every change detection run, immediately after ngOnChanges and ngOnInit.
ngAfterViewInitAfterViewInitCalled once after the component's view and its children's views are initialized.

Implementing OnInit and OnDestroy

We implement the corresponding interface to ensure we fulfill the contract and provide the required method.

typescript import { Component, OnInit, OnDestroy } from '@angular/core';

@Component({ ... }) export class ClockComponent implements OnInit, OnDestroy { currentTime: string = ''; private timerInterval: any;

// 1. Initialization Logic ngOnInit(): void { console.log('ClockComponent initialized. Starting timer.'); this.timerInterval = setInterval(() => { this.currentTime = new Date().toLocaleTimeString(); }, 1000); }

// 2. Cleanup Logic ngOnDestroy(): void { console.log('ClockComponent destroyed. Clearing timer.'); if (this.timerInterval) { clearInterval(this.timerInterval); } } }

Using ngOnDestroy is crucial to prevent memory leaks, especially when dealing with subscriptions or intervals that persist outside the component's existence.