简体   繁体   English

每次更改角度值时如何检测变量的变化

[英]How to detect a change in a variable when everytime its value is changed in angular

I would like to detect the change in variable which is of type int everytime the value is changed based on that i have do few operations to be performed .我想检测每次更改值时类型为 int 的变量的更改,因为我执行的操作很少。

The variable is int value which changes on button click.变量是 int 值,它会在单击按钮时发生变化。

I have tried it using @Input which is totally doesn't suit my requirement.我已经尝试过使用 @Input 这完全不符合我的要求。

addWhereCondition() {
    ++this.numberOfWhereConditions;
  }
  deleteWhereCondition() {
    if (this.numberOfWhereConditions > 1) {
      --this.numberOfWhereConditions;
    } else {
      this.numberOfWhereConditions = 1;
    }
  }

numberOfWhereConditions is the variable which is changed and need to detect that change numberOfWhereConditions 是已更改且需要检测该更改的变量

You can create a getter and setter for it.您可以为它创建一个 getter 和 setter。 Before the constructor...在构造函数之前...

private _numberOfWhereConditions: number;

get numberOfWhereConditions(): number {
    return this._numberOfWhereConditions
}

set numberOfWhereConditions(newNum: number) {
    if (this._numberOfWhereConditions !== newNum) { // if the new number is not the same as the old number 
    // Logic for what happens when there is a change detected
    this._numberOfWhereConditions = newNum; // You do need to explicitly set the new number
}

Within the HTML, you would call numberOfWhereConditions and within the typescript, you would call this.numberOfWhereConditions .在 HTML 中,您将调用numberOfWhereConditions而在打字稿中,您将调用this.numberOfWhereConditions

Here's a tutorial article .这是一篇教程文章

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM