[SOLVED] Filter by boolean value angular

Issue

im trying to make a filter by the status of the user, "Ativo" for online and "Inativo" for offline, but filtering by string is giving me some headache because when i type "ativo" all the offline users still show up because the word "ativo" exists in "inativo". So i wanted to attach a false value to ‘inativo’ and a true to ‘ativo’.

Any tips on how do i do that? I still what the filter to show "Ativo" and "Inativo" as the options in the datalist, but when selected it should send a true or false value to the filter function

This are the html and the function on ts i created

<input type="text" list="status" placeholder="Status" (keyup)="updateFilter($event)" id="stat">   
    <datalist id="status">
      <option>Ativo</option>
      <option>Inativo</option>
    </datalist>
updateFilter(event: Event) {
    this.filterValue = (event.target as HTMLInputElement).value;    
    this.dataSource.filter = this.filterValue.trim().toLowerCase();
    console.log(this.dataSource.filter);

    if (this.dataSource.paginator) {
      this.dataSource.paginator.firstPage();
    }
  }

Solution

Angular Material provides a way to say how the filter should be applied to the data via the filterPredicate method: https://material.angular.io/components/table/api#MatTableDataSource

Providing an arrow function to your datasource that says values should strictly be equal instead of alike should solve you problem.

this.datasource.filterPredicate = (data: YourDataType, filter: string) => {
  return data.status === filter;
};

Answered By – Ocunidee

Answer Checked By – Terry (BugsFixing Volunteer)

Leave a Reply

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