Lazloman
Lazloman

Reputation: 1347

Detect internal change to @Input property angular 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

Upvotes: 4

Views: 5353

Answers (3)

Wand Maker
Wand Maker

Reputation: 18762

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.

Upvotes: 2

ランス
ランス

Reputation: 550

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

Upvotes: -1

Sajeetharan
Sajeetharan

Reputation: 222682

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 
}

Upvotes: 7

Related Questions