【问题标题】:How to listen to a property in Angular?如何在 Angular 中监听属性?
【发布时间】:2019-09-29 03:49:32
【问题描述】:

我对角度有疑问。如何监听同一个类的属性值变化。

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

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

export class AppComponent  { 
  name:string
}

【问题讨论】:

  • 你想做什么。请解释您的问题
  • 你可以使用 typescript setter 和 getter 在属性改变时做一些事情。
  • 我认为 ngOnChanges 仅适用于 Input 属性。

标签: javascript angular properties


【解决方案1】:

在您的情况下对属性更改采取行动的一种简单方法是为您的属性实现 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
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-16
    • 2023-02-08
    • 1970-01-01
    • 2012-07-08
    • 2018-08-21
    • 2021-05-05
    相关资源
    最近更新 更多