Gargoyle
Gargoyle

Reputation: 10375

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.

Upvotes: 3

Views: 21659

Answers (2)

gmazzotti
gmazzotti

Reputation: 427

You only need to create a getter who count the number of checked element and bind it in you component template. Angular will call it at every change detection interation and update the value displayed. So in your component something like:

get checkedTotal() {
    var count = 0;
    for(var i = 0; i < this.filteredElements.length; ++i){
        if( this.filteredElements[i].checked )
            count++;
    }
    return count;
}

and in your component template just add

Checked: {{checkedTotal}}

Upvotes: 0

Abbas Amiri
Abbas Amiri

Reputation: 3214

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

Upvotes: 6

Related Questions