1

Suppose I have component with

@Input() timeData: TimeData

where TimeData contains only one field: time.

I want to observe timeData.time, assuming that only timeData.time was changed (not the whole timeData)

ngOnChanges doesn't track such change, while {{timeData.time}} works perfect.

My final goal is to set flag goodTime

if(timeData.time % 10 === 0){
    goodTime = true
}

2 Answers2

5

You don't provide information about how your TimeData looks like but when you add an EventEmitter you can subcribe to changes.

class TimeData {
  _time: number;
  get time(): number {
    return this._time;
  }
  set time(value: number) {
    this._time = number;
    timeChange.next(number);
  }
  timeChange: EventEmitter<number> = new EventEmitter<number>();
} 

use it like

timeData.timeChange.subscribe((value) => { doSomething(value);}
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • Yes - this is exactly what I needed. Thank you so much :-) However I wonder how Angular2 does it. {{timeData.time}} works, without additional fields (timeChange, _time). – duo_pendulum Feb 02 '16 at 21:54
  • All bindings are checked in each change detection cycle. You could do this as well by implementing `doCheck()` in your component and compare the previous value with the current one. – Günter Zöchbauer Feb 03 '16 at 04:25
0

I did't noticed that before, but someone else also posed similar question:

How to get onChanges for properties changed on an object sent in for an @Input

Community
  • 1
  • 1