Detecting Input Binding Changes
Learn how to detect the input binding changes using lifecycle hooks of the Angular component.
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:
Import the
OnChangesandSimpleChangesartifacts in theproduct-detail.component.tsfile.
import { Component, Input, Output, EventEmitter, OnChanges, SimpleChanges } from '@angular/core';
Modify the definition of the
ProductDetailComponentclass so that it implements theOnChangesinterface.
export class ProductDetailComponent implements OnChanges
Implement the
ngOnChangesmethod that is defined in theOnChangesinterface. It accepts an object of typeSimpleChangesas a parameter that contains one key for each input property that changes. Each key points to another object with the propertiescurrentValueandpreviousValue, which denote the new and the old value of the input property, respectively.
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 ...