Angular 6 filter table with checkboxes

I have this working snippet. I want to filter a table using checkboxes. The problem is when I check a for example, it gives me the filtered array. But when I uncheck it, I want to return me the original array.

.html

<ng-container *ngFor="let group of groups">
    <label class="btn btn-filter" id="bttns">
    <input type="checkbox" name="customersGroupFilter" autoComplete="off" [value]="group" (change)="changeGroup($event)">
    {{ group }}
  </label>&nbsp;
</ng-container>

<table>
  <thead>
    <tr>
      <th>Name</th>
      <th>Group</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let user of newArray">
      <td>{{user.name}}</td>
      <td>{{user.group}}</td>
    </tr>
  </tbody>
</table>

.ts

  changeGroup(event) {
    const group = event.target.value;
    const index = this.groupValue.indexOf(group);

    if (index > -1) {
      this.groupValue.splice(index, 1);
    } else {
      this.groupValue.push(group);
    }

    this.transform(this.usersList, 'group', this.groupValue)
  }

  transform(items: any[], field: string, value: string[]): any[] {
    console.log(value)
    if (!items) {
      return [];
    }
    if (!field || !value || value.length <= 0) {
      return items;
    }

    this.newArray = items.filter(singleItem => {
      return (singleItem != null && singleItem[field] != null && singleItem[field] != undefined && value.indexOf(singleItem[field]) >= 0);
    });

    return this.newArray
  }

How can I modify this code in order to obtain what I want?

I tried something with a condition like this in changeGroup()

if (this.groupValue.length == 0) {
   this.transform(this.usersList, '', this.groupValue)
}

Also, is this a good way to filter a table? I tried avoiding pipe filters. Thank you for your time!

Source: Angular

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.