简体   繁体   中英

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 .

The variable is int value which changes on button click.

I have tried it using @Input which is totally doesn't suit my requirement.

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

You can create a getter and setter for it. 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 .

Here's a tutorial article .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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