Angular Lifecycle Hooks

Angular Lifecycle Hooks

Every Angular component has a strict lifecycle managed entirely by the framework.

Angular creates the component, renders it, checks for data changes, and eventually destroys it.

Lifecycle hooks allow you to tap into these specific moments and execute custom code.


What are Lifecycle Hooks?

Lifecycle hooks are simply methods that you define in your TypeScript component class.

Angular automatically looks for these specific method names and calls them at the right time.

To use them properly, your class should implement the corresponding interface from @angular/core.


The ngOnInit Hook

The ngOnInit hook is the most commonly used lifecycle hook in Angular.

It is called exactly once, right after Angular has initialized all data-bound properties.

This makes it the perfect place to fetch initial data from an API or set up your component state!

ngOnInit Example:

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

@Component({ selector: 'app-dashboard', template: '<p>Dashboard loaded!</p>' }) export class DashboardComponent implements OnInit {

// The constructor should only be used for dependency injection constructor(private apiService: ApiService) {}

// ngOnInit is used for actual initialization logic ngOnInit() { console.log('Component initialized! Fetching data...'); // this.apiService.getData().subscribe(...); } }


The ngOnDestroy Hook

The ngOnDestroy hook is called right before Angular destroys the component and removes it from the DOM.

This is the critical place to perform cleanup operations.

If you have custom event listeners, active intervals, or open RxJS subscriptions, you must unsubscribe here to prevent massive memory leaks!

ngOnDestroy Example:

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

@Component({ selector: 'app-timer', template: '<p>Timer is running...</p>' }) export class TimerComponent implements OnDestroy { timerId = setInterval(() => console.log('Tick'), 1000);

ngOnDestroy() { // We MUST clear the interval when the component is destroyed! clearInterval(this.timerId); console.log('Component destroyed, timer cleared.'); } }


Other Important Hooks


Exercise 1 of 2

?

Which lifecycle hook is the recommended place to perform initial data fetching requests?

Exercise 2 of 2

?

What is the primary purpose of the ngOnDestroy hook?