duo_pendulum
duo_pendulum

Reputation: 61

Angular2. How to observer sub-object changes?

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
}

Upvotes: 1

Views: 1090

Answers (2)

duo_pendulum
duo_pendulum

Reputation: 61

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

Upvotes: 0

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657068

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);}

Upvotes: 5

Related Questions