Kin
Kin

Reputation: 4596

How to detect if property changed in Angular 2?

I have simple class which looks like this:

export class MessagesPage  {

    @ViewChild(Content) content: Content;

    public message  = '';
    public messages = [];

    public state = 'general';
}

Is it possible inside the class to detect if state property is changed?

Upvotes: 0

Views: 425

Answers (1)

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

Reputation: 658037

Make them getters and setters. There is no other way to get notified about changes:

export class MessagesPage  {

    @ViewChild(Content) content: Content;

    public message  = '';
    public messages = [];

    private _state = 'general';
    public get state() { return this._state; }
    public set state(value:string) { 
      this._state = value;
      console.log('state changed', this._state);
    }
}

Upvotes: 5

Related Questions