Angular 20

Angular Lifecycle Hooks Tutorial – ngOnInit, ngOnDestroy & More in Angular 20

Chapter 13: Angular Lifecycle Hooks (Standalone Components)

Angular components have a lifecycle managed by Angular itself. Lifecycle hooks allow you to tap into key moments during a component’s existence to perform initialization, cleanup, or update tasks. This chapter explains important lifecycle hooks, their usage, and optimization tips for standalone components.

1. What Are Lifecycle Hooks?

Lifecycle hooks are methods Angular calls at specific phases of a component or directive lifecycle. They let you run custom code when components are created, updated, or destroyed.

2. Common Lifecycle Hooks

ngOnInit()

Called once after the component’s first display. Ideal for initialization logic like fetching data or setting up default values.

ngOnChanges(changes: SimpleChanges)

Called when any data-bound input property changes. Receives a SimpleChanges object describing the changes. Useful for reacting to input updates.

ngDoCheck()

Called during every change detection run, useful for custom change detection beyond Angular’s default.

ngAfterContentInit()

Called after Angular projects external content into the component’s view (via <ng-content>).

ngAfterViewInit()

Called after Angular initializes component’s views and child views. Good for DOM-dependent logic.

ngOnDestroy()

Called just before Angular destroys the component. Use this to clean up subscriptions, timers, or other resources.

3. Using Lifecycle Hooks in Standalone Components

Standalone components implement lifecycle hooks just like regular components. Here’s an example demonstrating some key hooks:


import { Component, OnInit, OnDestroy, Input, SimpleChanges, OnChanges } from '@angular/core';

@Component({
  standalone: true,
  selector: 'app-lifecycle-demo',
  template: `

Current count: {{ count }}

` }) export class LifecycleDemoComponent implements OnInit, OnChanges, OnDestroy { @Input() count = 0; ngOnInit() { console.log(‘ngOnInit – component initialized’); } ngOnChanges(changes: SimpleChanges) { console.log(‘ngOnChanges – input changed’, changes); } ngOnDestroy() { console.log(‘ngOnDestroy – cleanup before destroy’); } }

4. Optimization Tips

  • Avoid expensive logic in ngDoCheck since it runs frequently.
  • Unsubscribe from Observables and detach event listeners in ngOnDestroy to prevent memory leaks.
  • Use OnPush change detection strategy where possible to improve performance.

5. Summary

  • Lifecycle hooks provide fine control over component behavior at different stages.
  • ngOnInit and ngOnDestroy are the most commonly used hooks.
  • Proper use of hooks and cleanup improves app stability and performance.

Next Chapter Preview

Up next, Chapter 14 explores Angular Animations — learn to create smooth UI animations like fade, slide, and expand transitions.

Leave a Reply

Your email address will not be published. Required fields are marked *