kogibail
kogibail

Reputation: 135

How to detect Angular life cycle hook OnChanges

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');
  }
}

Upvotes: 2

Views: 1882

Answers (2)

DeborahK
DeborahK

Reputation: 60518

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);
}

Upvotes: 1

Justin Degonda
Justin Degonda

Reputation: 103

I notice you have not imported or implemented your lifecycle hooks. Try doing this:

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

        @Component( { template:`
          <div>
            hello life
            <input type="text" placeholder="hassan" />
          </div> `, 
          selector:'hook-life' } ) 

        export class LifeCycleComponent implements OnInit, OnDestroy, OnChanges { 

        constructor(){ console.log("constructor ")} 

        ngOnChanges(c:SimpleChange) { console.log(`onchanges ${c.currentValue} `); } 
        ngOnInit() { console.log("onInit") } 
        ngOnDestroy() { console.log("onDestroy")
        } }

Upvotes: 3

Related Questions