Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2: how do I detect attribute changes to input attributes on a Component?

Tags:

angular

I've got an Angular 2 Controller which looks like this:

@Component({
  selector: 'my-component',
  template: '<div>The value is: {{ value }}</div>',
})
class MyComponent implements OnInit {
  @Input()
  value: string;

  @Output
  valueChange = new EventEmitter<number>();

  ngOnInit() {
    this.valueChange.subscribe(value => {
      console.log('new value:', value); // <-- does not get triggered
    });
  }
}

But when the value of value changes from a template binding:

<my-component [value]="someValue" /> <!-- valueChange not triggered! -->

The valueChange event isn't triggered so, even though the template correctly updates and shows the new value, the component doesn't know it's been changed.

How can I detect when input attributes on my controller are changed?

like image 743
David Wolever Avatar asked Aug 08 '16 01:08

David Wolever


1 Answers

In my opinion, Output is for your component to emit event to others so they would update their view if necessary, it should only be used for changes made internally that need to be broadcast out (hence the name Output). Triggering an Output event on Input changes may cause unexpected behavior (as now that valueChange is triggered for all the changes both inside and outside, and not really an Output anymore).

In your case, if you want to do stuff when your value changes, you can make it a setter:

private _value: string;
get value(): string {
  return this._value;
}

@Input('value')
set value(val: string) {
  this._value = val;
  console.log('new value:', value); // <-- do your logic here!
}
like image 108
Harry Ninh Avatar answered Sep 24 '22 20:09

Harry Ninh