如何在Angular中收听属性?

时间:2019-05-11 14:08:51

标签: javascript angular properties

我对棱角有疑问。如何侦听同一类中的属性值更改。

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})

export class AppComponent  { 
  name:string
}

1 个答案:

答案 0 :(得分:0)

根据情况对属性进行更改的一种简单方法是为属性实现getter和setter。

示例:

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})

export class AppComponent  { 
  private _name: string

  set name(data) {
    this._name = data;

    // here you can trigger something on data change
    // do something when data is assigned to name
  }

  get name() {
    return this._name;
  }

  //another example for setters as @Input properties
  //here you will act if the component receives input change
  //from a parent component
  @Input
  set name(data: any) {
    this._name = data;

    // here you can trigger something on data change
    // do something when data is assigned to name
  }
}