Issue
I have a table with two filter options "Gender" and "Country"! Essentially the filter works, that is I click on the gender dropdown for male or female and the table shows me all the the entries. My issue is, with the way that I have done, I always have to refresh(as in reload the data) the table before I can filter again. Say I have filter for females, I can't directly click on male to show me the male entries, I have to refresh and then I can only filter again. I'm sure its only a matter of one or two lines of code but I just can't seem to figure it out.
Below my methods:
filterByGender(event) {
let gender = event;
if (gender === "Male") {
gender = "M";
} else if (gender === "Female") {
gender = "F";
}
let filteredGender = this.customerArray
.filter(customer => customer.gender === gender);
console.log("filteredGender", filteredGender);
this.customerArray = filteredGender;
}
filterByCountry(event) {
let country = event;
let filteredCountry = this.customerArray
.filter(customer => customer.countryCode === country);
this.customerArray = filteredCountry;
}
this.customerArray is the array of all the customers from the backend. Now the reason its not working the way I want to is because I refill the array so I can't do a second filter, but what would be a way around this?
Solution
You can actually use Angular Pipe with this if you want to filter your table based on the selected value on your select box
Created 2 Stackblitz Demo based on your preference:
Single Filter Pipe for Table List - Filter by Gender only
Multiple Selection Filter Pipe for Table List - Filter by Gender & Country
TableFilterPipe
Import TableFilterPipe on your Module's Declarations
@Pipe({
name: 'tableFilter'
})
export class TableFilterPipe implements PipeTransform {
transform(list: any[], value: string) {
// If there's a value passed (male or female) it will filter the list otherwise it will return the original unfiltered list.
return value ? list.filter(item => item.gender === value) : list;
}
}
CustomComponent
@Component({
...,
template: `
<select [(ngModel)]="gender">
<option value="male">Male</option>
<option value="female">Male</option>
</select>
<table>
...
<tr *ngFor="let user of users | tableFilter: gender"> // Use your pipe here, so whenever there's a change on selectbox, it will filter the list based on the value assigned.
<td>{{ user.name }}</td>
<td>{{ user.gender }}</td>
</tr>
</table>
`
})
export class CustomComponent {
gender: string;
users: any[] = [...];
}
Answered By - KShewengger
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.