如何检测Angular 2中的属性是否已更改? [英] How to detect if property changed in Angular 2?

查看:81
本文介绍了如何检测Angular 2中的属性是否已更改?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的类,看起来像这样:

I have simple class which looks like this:

export class MessagesPage  {

    @ViewChild(Content) content: Content;

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

    public state = 'general';
}

是否可以在类内部检测state属性是否已更改?

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

推荐答案

使它们成为getter和setter.没有其他方法可以获取有关更改的通知:

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

这篇关于如何检测Angular 2中的属性是否已更改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆