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();
}
}
CodePudding user response:
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;
};
CodePudding user response:
First, if your filter has strict value, you shouldn't use datalist but select
. It works the same but doesn't allow the user to type in the input.
Now, there is no reason you encounter this kind of problem. Just checking if (event.target as HTMLInputElement).value === 'ativo'
should be enough.
I recommand creating an enum to avoid magic string in your code, so instead of 'ativo'
you will have UserStatus.ativo
.
CodePudding user response:
You can use regex to do that :
var myString = 'ativio';
var myString2 = 'inativio';
new RegExp('\bativio\b').test(myString); // true
new RegExp('\bativio\b').test(myString2); // false