我有一个带有两个过滤器选项“性别”和“国家/地区”的表格!从本质上讲,该过滤器有效,也就是说,我单击了男性或女性的性别下拉列表,该表显示了所有条目。我的问题是,按照我的方式,在重新过滤之前,我总是必须刷新(如重新加载数据)表。假设我有针对女性的过滤器,我不能直接单击男性以显示男性条目,我必须刷新然后只能再次过滤。我敢肯定这只是一两行代码的问题,但是我似乎无法弄清楚。
在我的方法下面:
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是后端中所有客户的数组。现在,它无法按我想要的方式工作的原因是因为我重新填充了数组,所以无法执行第二个过滤器,但是如何解决这个问题呢?
答案 0 :(得分:0)
如果要基于选择框上的选定值过滤表,则可以实际使用Angular Pipe
根据您的喜好创建了 2 Stackblitz演示 :
Single Filter Pipe for Table List-仅按性别过滤
Multiple Selection Filter Pipe for Table List-按性别和国家/地区过滤
TableFilterPipe
在您的模块的声明
上导入TableFilterPipe
@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[] = [...];
}
答案 1 :(得分:0)
transform(items: Incident[], location_id: string, driver_id: string,
description: string, type: string,technician_id: string){
if (items && items.length){
return items.filter(item =>{
if (location_id && item.location_id.name.toLowerCase().indexOf(location_id.toLowerCase()) === -1){
return false;
}
if (driver_id && item.driver_id.name.toLowerCase().indexOf(driver_id.toLowerCase()) === -1){
return false;
}
if (description && item.description.toLowerCase().indexOf(description.toLowerCase()) === -1){
return false;
}
if (type && item.incidenttype_id.name.toLowerCase().indexOf(type.toLowerCase()) === -1){
return false;
}
if (technician_id && item.technician_id.name.toLowerCase().indexOf(technician_id.toLowerCase()) === -1){
return false;
}
return true;
})
}
else{
return items;
}
}
enter code here