[Fixed] How to detect Angular life cycle hook OnChanges

Issue

In this simple component with only one input box and two-way binding I wanted to test OnChanges life cycle hook by logging to console when I type into input. ngOnChanges is not logging to console. ngOnInit is. What is the best way to make it work?

import { Component, SimpleChange } from '@angular/core';

@Component({
  template: `
    <div>
      hello life
      <input type="text" placeholder="hassan" [(ngModel)]="name" />
      <p>my name is:{{ name }}</p>
    </div>
  `,
  selector: 'hook-life',
})
export class LifeCycleComponent {
  name: string = '';
  constructor() {
    console.log('constructor ');
  }

  ngOnChanges(c: SimpleChange) {
    console.log(`onchanges ${c.currentValue} `);
  }

  ngOnInit() {
    console.log('onInit');
  }

  ngOnDestroy() {
    console.log('onDestroy');
  }
}

Solution

To watch for changes to an input element in the component, use a getter and setter like this:

private _name: string;
get name(): string {
    return this._name;
}
set name(value: string) {
    this._name = value;
    console.log(this.name);
}

Leave a Reply

(*) Required, Your email will not be published