Tuesday, 29 May 2018

Angular - Intercept input property changes with ngOnChanges()

Detect and act upon changes to input property values with the ngOnChanges() method of the OnChanges lifecycle hook interface.
You may prefer this approach to the property setter when watching multiple, interacting input properties.
This VersionChildComponent detects changes to the major and minor input properties and composes a log message reporting these changes:
import { Component, Input, OnChanges, SimpleChange } from '@angular/core';

  selector: 'app-version-child',
  template: `
    <h3>Version {{major}}.{{minor}}</h3>
    <h4>Change log:</h4>
      <li *ngFor="let change of changeLog">{{change}}</li>
export class VersionChildComponent implements OnChanges {
  @Input() major: number;
  @Input() minor: number;
  changeLog: string[] = [];

  ngOnChanges(changes: {[propKey: string]: SimpleChange}) {
    let log: string[] = [];
    for (let propName in changes) {
      let changedProp = changes[propName];
      let to = JSON.stringify(changedProp.currentValue);
      if (changedProp.isFirstChange()) {
        log.push(`Initial value of ${propName} set to ${to}`);
      } else {
        let from = JSON.stringify(changedProp.previousValue);
        log.push(`${propName} changed from ${from} to ${to}`);
    this.changeLog.push(log.join(', '));
The VersionParentComponent supplies the minor and major values and binds buttons to methods that change them.
import { Component } from '@angular/core';

  selector: 'app-version-parent',
  template: `
    <h2>Source code version</h2>
    <button (click)="newMinor()">New minor version</button>
    <button (click)="newMajor()">New major version</button>
    <app-version-child [major]="major" [minor]="minor"></app-version-child>
export class VersionParentComponent {
  major = 1;
  minor = 23; 
  newMinor() {

  newMajor() {
    this.minor = 0;
Here's the output of a button-pushing sequence:

No comments:

Post a Comment