4

I understand that ngOnChanges is fired when a components @Input property from its parent component. But how I can detect if an @Input property is changed within its component. I've not been able to find a good answer to that. Thanks

Lazloman
  • 1,289
  • 5
  • 25
  • 50

3 Answers3

6

To do this, You can use the ngOnChanges() lifecycle method as also mentioned in older answers:

@Input() yourInput: string;

ngOnChanges(changes: SimpleChanges) {
    this.doSomething(changes.yourInput.currentValue);
    // You can also use yourInput.previousValue and 
}
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
1

You can define @Input() on setter methods so that you can take additional actions whenever new values is being set for an attribute.

Here is a sample component that demonstrates this:

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

@Component({
  selector: 'hello',
  template: `<h1 (click)="name = 'Bye'">{{name}}!</h1>`,
  styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent {

  private _name: string;

  get name() {
    console.log("Returning name", this._name);
    return this._name;
  }

  @Input() 
  set name(newName) {
    console.log("Setting new name", newName);
    this._name = newName;
  }
}

This component when used in another component, can be specified somewhat like below:

  <hello  [name]="'Hi'"></hello>  

In aboe example, initial value of Hi was set from external/parent component, and on click of text, value is updated to Bye internal to component. In both cases, you will observe the console.log statement in browser console.

Wand Maker
  • 18,476
  • 8
  • 53
  • 87
0

You can use an Output() or event emitter which needs to be caught by the parent component.

ランス
  • 418
  • 2
  • 8