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

3 Answers 3

7

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 
}
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

-1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.