Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Track variable change in Angular 5

I have a simple class which defines a checked variable as a boolean. My component then has an array of those objects, and the HTML shows each one.

<tr *ngFor="let element of filteredElements">
    <td>
      <input type="checkbox" [checked]="element.checked" (change)="onCheckChanged(element)">

Now I want to add a display value that tells me how many items are checked at any given point. I'm not sure how to have the component "watch" all of those elements. I could change the value of checked from many different places.

I'm feeling like I need some type of Observable here but am not sure how to implement this.

like image 315
Gargoyle Avatar asked Dec 06 '25 13:12

Gargoyle


1 Answers

As far as I know, There are two methods to detect changes in internal state of angular classes.

Method 1:

You take charge of detection. In this way you need setter and getter for any member of your class that you need to be aware of their changes and emit an event.

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

export class ClassOne {
  private _state: boolean;
  stateChanged: EventEmitter<boolean> = new EventEmitter();

  set state(val: boolean) {
    this._state = val;
    this.stateChanged.emit(this._state);
  }

  get state(): boolean {
    return this._state;
  }

  stateChangedEmitter() {
    return this.stateChanged;
  }
}

then you can subscribe the stateChangedEmitter for any further actions.

Method 2:

You can delegate the change detection to Angular by implementing DoCheck

for more information and examples visit Angular ngDoCheck Life Cycle Hook

like image 64
Abbas Amiri Avatar answered Dec 08 '25 07:12

Abbas Amiri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!