Ido Ido - 3 months ago 20
AngularJS Question

how can I listen to changes in code in angular 2?

I'm using angular 2. I have a component with an input.
I want to be able to write some code when the input value changes.
The binding is working, and if the data is changed (from outside the component) I can see that there is change in the dom.

@Component({
selector: 'test'
})
@View({
template: `
<div>data.somevalue={{data.somevalue}}</div>`
})
export class MyComponent {

_data: Data;
@Input()
set data(value: Data) {
this.data = value;
}
get data() {
return this._data;
}

constructor() {
}

dataChagedListener(param) {
// listen to changes of _data object and do something...
}
}

Answer

You could use the lifecycle hook ngOnChanges:

export class MyComponent {
  _data: Data;
  @Input()
  set data(value: Data) {
    this.data = value;
  }
  get data() {
    return this._data;
  }

  constructor() {
  }

  ngOnChanges([propName: string]: SimpleChange) {
    // listen to changes of _data object and do something...
  }
}

This hook is triggered when:

if any bindings have changed

See these links for more details:

Comments