Search⌘ K
AI Features

Detecting Input Binding Changes

Explore how Angular's OnChanges lifecycle hook detects changes in input bindings within components. Understand implementing the ngOnChanges method to track old and new values, and use the AfterViewInit hook to access child components. This lesson helps you manage component communication and lifecycle events for better user experiences.

We'll cover the following...

The OnChanges lifecycle hook is called when Angular detects that the value of an input data binding has changed. We will use it in the product detail component to learn how it behaves when we select a different product from the list:

  1. Import the OnChanges and SimpleChanges artifacts in the product-detail.component.ts file.

TypeScript 4.9.5
import { Component, Input, Output, EventEmitter, OnChanges, SimpleChanges } from '@angular/core';
  1. Modify the definition of the ProductDetailComponent class so that it implements the OnChanges interface.

TypeScript 4.9.5
export class ProductDetailComponent implements OnChanges
  1. Implement the ngOnChanges method that is defined in the OnChanges interface. It accepts an object of type SimpleChanges as a parameter that contains one key for each input property that changes. Each key points to another object with the properties currentValue and previousValue, which denote the new and the old value of the input property, respectively.

TypeScript 4.9.5
ngOnChanges(changes: SimpleChanges): void {
const product = changes['name'];
const oldValue = product.previousValue;
const newValue = product.currentValue;
console.log(`Product changed from ${oldValue} to ${newValue}`);
}

The previous snippet tracks the name ...