Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 231
Lazloman Avatar asked Mar 05 '23 19:03

Lazloman


2 Answers

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 
}
like image 56
Sajeetharan Avatar answered Mar 12 '23 06:03

Sajeetharan


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.

like image 35
Wand Maker Avatar answered Mar 12 '23 07:03

Wand Maker