How to Use Angular Lifecycle Hooks

Angular lifecycle hooks provide precise control over component behavior at different stages of the component lifecycle. As the creator of CoreUI with over 11 years of Angular development experience, I use lifecycle hooks extensively to manage component initialization, data fetching, cleanup, and performance optimization. These hooks allow you to tap into key moments in a component’s life cycle.

Implement lifecycle hooks by importing the interfaces and adding the corresponding methods to your component class.

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

@Component({
  selector: 'app-user-profile',
  template: `
    <div>
      <h2>{{ user?.name }}</h2>
      <p>{{ user?.email }}</p>
    </div>
  `
})
export class UserProfileComponent implements OnInit, OnDestroy, OnChanges {
  @Input() userId: number
  user: any
  private subscriptions = new Subscription()

  ngOnChanges(changes: SimpleChanges): void {
    if (changes['userId'] && changes['userId'].currentValue) {
      this.loadUser(changes['userId'].currentValue)
    }
  }

  ngOnInit(): void {
    console.log('Component initialized')
    this.setupSubscriptions()
  }

  ngOnDestroy(): void {
    console.log('Component destroyed')
    this.subscriptions.unsubscribe()
  }

  private loadUser(id: number): void {
    // Load user data
  }

  private setupSubscriptions(): void {
    // Set up observables
  }
}

The most commonly used lifecycle hooks are ngOnInit() for component initialization, ngOnDestroy() for cleanup, and ngOnChanges() for responding to input property changes. Always implement the corresponding interfaces (OnInit, OnDestroy, etc.) for type safety. Use ngOnInit() for data fetching and setup, ngOnDestroy() for unsubscribing from observables and cleaning up resources, and ngOnChanges() to react to input property changes.

Best Practice Note:

In CoreUI components, we consistently implement lifecycle hooks for proper resource management, especially ngOnDestroy() to prevent memory leaks from observables. This practice ensures our enterprise-grade components remain performant and stable across complex applications with frequent component creation and destruction.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author

Subscribe to our newsletter
Get early information about new products, product updates and blog posts.
How to force a React component to re-render
How to force a React component to re-render

How to sleep in Javascript
How to sleep in Javascript

How to check if an element is visible in JavaScript
How to check if an element is visible in JavaScript

Why does querySelectorAll in TypeScript return Element instead of HTMLElement?
Why does querySelectorAll in TypeScript return Element instead of HTMLElement?

Answers by CoreUI Core Team