Thanks to visit codestin.com
Credit goes to coreui.io

How to Use ngOnChanges in Angular

The ngOnChanges lifecycle hook in Angular is called whenever input properties of a component change. As the creator of CoreUI with over 11 years of Angular development experience, I use ngOnChanges to react to parent component data changes and trigger appropriate responses in child components. This hook provides detailed information about what changed, including previous and current values.

Implement the OnChanges interface and ngOnChanges method to detect and respond to input property changes.

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

@Component({
  selector: 'app-product-card',
  template: `
    <div class="product-card">
      <h3>{{ product?.name }}</h3>
      <p>Price: {{ formattedPrice }}</p>
      <p>Status: {{ status }}</p>
    </div>
  `
})
export class ProductCardComponent implements OnChanges {
  @Input() product: any
  @Input() currency: string = 'USD'
  @Input() isActive: boolean = false

  formattedPrice: string = ''
  status: string = ''

  ngOnChanges(changes: SimpleChanges): void {
    // Check if product changed
    if (changes['product']) {
      console.log('Product changed from:', changes['product'].previousValue)
      console.log('Product changed to:', changes['product'].currentValue)

      if (!changes['product'].isFirstChange()) {
        this.updateProductData()
      }
    }

    // Check if currency changed
    if (changes['currency'] && this.product?.price) {
      this.updatePriceFormat()
    }

    // Check if active status changed
    if (changes['isActive']) {
      this.updateStatus()
    }
  }

  private updateProductData(): void {
    if (this.product) {
      this.updatePriceFormat()
      // Perform other product-related updates
    }
  }

  private updatePriceFormat(): void {
    if (this.product?.price) {
      this.formattedPrice = `${this.product.price} ${this.currency}`
    }
  }

  private updateStatus(): void {
    this.status = this.isActive ? 'Active' : 'Inactive'
  }
}

The ngOnChanges method receives a SimpleChanges object containing all changed input properties. Each property in SimpleChanges has previousValue, currentValue, and isFirstChange() method. Use isFirstChange() to differentiate between initial property setting and subsequent changes. The hook only triggers for input properties decorated with @Input(), not for internal component state changes.

Best Practice Note:

In CoreUI components, we use ngOnChanges extensively for dynamic theming, data transformation, and conditional rendering based on parent component state. This pattern ensures our reusable components respond appropriately to configuration changes while maintaining optimal performance through targeted updates.


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.
Mastering JavaScript List Comprehension: The Ultimate Guide
Mastering JavaScript List Comprehension: The Ultimate Guide

How to Hide Scrollbar with CSS
How to Hide Scrollbar with CSS

How to declare the optional function parameters in JavaScript?
How to declare the optional function parameters in JavaScript?

How to Use Bootstrap Tooltip in Vue 3 – The Right Way with CoreUI
How to Use Bootstrap Tooltip in Vue 3 – The Right Way with CoreUI

Answers by CoreUI Core Team