Master Angular From Scratch

Learn Angular with clear, interactive, and structured lessons for beginners and developers.

ANGULAR COURSE SYLLABUS
1. Angular Introduction
Angular Introduction Angular History Angular Fundamentals Angular Architecture Component-Based Angular
2. Angular Setup
Angular Setup Introduction Installing Node.js Installing Angular CLI Creating an Angular Application Angular Project Structure
3. Components
Components Overview Component Anatomy Creating Components Component Selector Component Template Component Styles Component Metadata Standalone Components Parent and Child Components Reusable Components
4. Templates
Templates Introduction Template Syntax Template Expressions Template Statements Template Reference Variables ng-template ng-container ngTemplateOutlet Built-in Control Flow
5. Data Binding
Data Binding Introduction Interpolation Binding Property Binding Event Binding Two-Way Data Binding Class & Style Binding
6. Directives
Directives Introduction Attribute Directives Structural Directives Custom Directives
7. Pipes
Pipes Introduction Built-in Pipes Parameterized Pipes Chaining Pipes Custom Pipes
8. Event Handling
Event Handling Introduction DOM Events Event Binding Syntax Event Object Passing Data to Event Handlers
9. Input & Output
Component Communication @Input @Output EventEmitter
10. Lifecycle Hooks
Lifecycle Hooks Introduction ngOnInit ngOnChanges ngAfterViewInit ngOnDestroy
11. Services
Services Introduction Creating Angular Services Using Services in Components Sharing Data Through Services Service Scope
12. Dependency Injection
Dependency Injection Introduction Injecting Dependencies InjectionToken Provider Configuration
13. Routing
Routing Introduction Route Configuration RouterLink & Navigation Route Parameters Child Routes Route Guards
14. Forms
Angular Forms Introduction Template-Driven Forms Reactive Forms Form Validation Form Submission & Error Handling
15. HttpClient
HttpClient Introduction Configuring HttpClient GET Request POST, PUT & DELETE Requests Headers & Parameters HTTP Error Handling
16. Observables
Observables Introduction Creating & Subscribing to Observables Observable Data Streams Observable Operators Subscription Management
17. RxJS
RxJS Introduction RxJS Operators Transformation & Filtering Combining Observables Higher-Order Mapping Subjects
18. API Integration
API Integration Introduction Connecting Angular with REST API Consuming API Data CRUD API Integration API Response & Error Handling

Angular OnDestroy

Angular @OnDestroy is a lifecycle hook used to perform cleanup work just before a component or directive is destroyed.

What is @OnDestroy?

The ngOnDestroy() lifecycle hook is called once just before Angular destroys a component, directive, or service instance that is no longer required.

It is commonly used to clean up subscriptions, timers, event listeners, resources, and other ongoing activities.

Simple Definition

ngOnDestroy() is the place where cleanup logic is performed before a component is removed from the UI.

Where @OnDestroy Fits in Angular Lifecycle

Component Component is active
→
Application Runs Timers / subscriptions active
→
ngOnDestroy() Cleanup logic runs
→
Component Removed Instance is destroyed

Basic Syntax

To use this lifecycle hook, implement the OnDestroy interface and define the ngOnDestroy() method.

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

@Component({
    selector: 'app-dashboard',
    templateUrl: './dashboard.component.html'
})
export class DashboardComponent implements OnDestroy {

    ngOnDestroy(): void {

        console.log('Component destroyed');

    }

}
Important

Angular automatically calls ngOnDestroy() before destroying the component.

Why Use @OnDestroy?

Clear Timers

Stop intervals or timeouts created by the component.

clearInterval()
Unsubscribe

Clean up active subscriptions when required.

unsubscribe()
Remove Events

Remove manually registered event listeners.

removeEventListener()
Release Resources

Release resources created during component execution.

cleanup()

1. Simple OnDestroy Example

The following example shows a cleanup message when the component is about to be destroyed.

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

@Component({
    selector: 'app-course',
    templateUrl: './course.component.html'
})
export class CourseComponent implements OnDestroy {

    ngOnDestroy(): void {

        console.log(
            'Course component is being destroyed'
        );

    }

}
How it works

When Angular removes the course component from the view, ngOnDestroy() is automatically executed.

2. Cleaning Up a Timer

If a component creates a timer, the timer should be cleared when the component is destroyed.

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

@Component({
    selector: 'app-clock',
    templateUrl: './clock.component.html'
})
export class ClockComponent implements OnDestroy {

    timerId: any;

    constructor() {

        this.timerId = setInterval(() => {

            console.log('Timer running...');

        }, 1000);

    }

    ngOnDestroy(): void {

        clearInterval(this.timerId);

        console.log('Timer cleared');

    }

}
Expected Behavior:

While the component is active: Timer running...

Before the component is removed: Timer cleared

3. Cleaning Up a Subscription

A component may subscribe to an Observable. The subscription can be cleaned up when the component is destroyed.

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

@Component({
    selector: 'app-course-list',
    templateUrl: './course-list.component.html'
})
export class CourseListComponent
    implements OnInit, OnDestroy {

    courseSubscription!: Subscription;

    ngOnInit(): void {

        this.courseSubscription =
            this.courseService.getCourses()
                .subscribe(data => {

                    console.log(data);

                });

    }

    ngOnDestroy(): void {

        this.courseSubscription?.unsubscribe();

        console.log(
            'Course subscription cleaned up'
        );

    }

}
Important Point

Cleanup is important when a subscription or other ongoing resource should no longer remain active after the component leaves the UI.

4. Removing Event Listeners

When an event listener is manually registered, it should also be removed when the component is destroyed.

Component
export class DashboardComponent
    implements OnInit, OnDestroy {

    handleResize = () => {

        console.log(window.innerWidth);

    };

    ngOnInit(): void {

        window.addEventListener(
            'resize',
            this.handleResize
        );

    }

    ngOnDestroy(): void {

        window.removeEventListener(
            'resize',
            this.handleResize
        );

    }

}
ngOnInit() Add Event Listener
→
Component Active Event Listener Works
→
ngOnDestroy() Remove Listener

5. OnDestroy with Conditional Rendering

A component can be created and destroyed depending on application state. The OnDestroy hook runs when Angular removes the component.

Template
<app-course
    *ngIf="showCourse">
</app-course>

<button (click)="showCourse = !showCourse">

    Toggle Course

</button>
Component
showCourse = true;
How it works

When showCourse becomes false, Angular removes the component and calls its ngOnDestroy() method.

6. Using OnInit and OnDestroy Together

A common pattern is to start a resource in ngOnInit() and clean it up in ngOnDestroy().

Example
timerId: any;

ngOnInit(): void {

    this.timerId = setInterval(() => {

        console.log('Working...');

    }, 1000);

}

ngOnDestroy(): void {

    clearInterval(this.timerId);

    console.log('Cleanup completed');

}
ngOnInit() Start Resource
→
Component Active Resource in use
→
ngOnDestroy() Cleanup Resource

@OnInit vs @OnDestroy

ngOnInit() ngOnDestroy()
Used for component initialization. Used for component cleanup.
Runs during component initialization. Runs before component destruction.
Can start timers, subscriptions, or data loading. Can stop timers and clean up subscriptions.
Prepares resources for component execution. Releases resources no longer required.

Complete CIIT Training Institute Example

Suppose CIIT Training Institute has a live course dashboard. When the dashboard opens, it starts a timer. When the dashboard is closed or removed, the timer should be cleared using ngOnDestroy().

live-dashboard.component.ts
import {
    Component,
    OnInit,
    OnDestroy
} from '@angular/core';

@Component({
    selector: 'app-live-dashboard',
    templateUrl: './live-dashboard.component.html'
})
export class LiveDashboardComponent
    implements OnInit, OnDestroy {

    timerId: any;

    status = '';

    ngOnInit(): void {

        this.status =
            'Live Dashboard Active';

        this.timerId = setInterval(() => {

            console.log(
                'Checking live training status...'
            );

        }, 5000);

    }

    ngOnDestroy(): void {

        clearInterval(this.timerId);

        console.log(
            'Live Dashboard Cleanup Completed'
        );

    }

}
live-dashboard.component.html
<div>

    <h2>
        CIIT Training Institute
    </h2>

    <p>
        {{ status }}
    </p>

</div>
Expected Output:

CIIT Training Institute

Live Dashboard Active

When the component is destroyed, the timer is cleared automatically through ngOnDestroy().

Important Points About @OnDestroy

  • ngOnDestroy() is called before Angular destroys a component.
  • It is mainly used for cleanup operations.
  • Timers can be stopped during component destruction.
  • Subscriptions can be cleaned up when they are no longer needed.
  • Manually registered event listeners should be removed.
  • Cleanup helps prevent unnecessary ongoing work after a component is removed.

@OnDestroy Best Practices

  • Keep cleanup logic inside ngOnDestroy().
  • Clear timers created by the component.
  • Clean up subscriptions when required.
  • Remove manually attached browser event listeners.
  • Release resources that are no longer required.
  • Keep cleanup code simple and easy to maintain.

Summary

Angular @OnDestroy provides the ngOnDestroy() lifecycle method for performing cleanup work before a component or directive is destroyed.

It is commonly used to clear timers, clean up subscriptions, remove event listeners, and release resources created while the component was active.