我正在使用管道来过滤数据表中三个不同列的数据。
该列的名称为category
,name
,department
。
我传递的论点如下:
<table class="table table-striped" [mfData]="listdata | dataFilter : filtername : filterDep : filterCategory">
我有*ngFor
循环:
<tr *ngFor="let item of mf.data; let i =index">
<td>
{{i+1}}
</td>
<td>{{ item.name }}</td>
<td>{{item.department}}</td>
<td>{{item.category}}</td>
</tr>
设置查询变量的代码是
<th colspan="2">
Filter by name:
<input class="form-control" [(ngModel)]="filtername" (input)="change()" />
</th>
<th colspan="1">
Filter by Department:
<input class="form-control" [(ngModel)]="filterDep" (input)="change()" />
</th>
<th colspan="1">
Filter by Category:
<input class="form-control" [(ngModel)]="filterCategory" (input)="change()" />
</th>
我的数据中category
的某些内容为null
。
我使用的管道是:
@Pipe({
name: "dataFilter"
})
export class DataFilterPipe implements PipeTransform {
transform(array: any[], query: string, query2: string, query3: string): any {
let notNullCategory = _.reject(array, ['category', null]);
if (query || query2 || query3) {
return _.filter(notNullCategory, row => ((row.name.indexOf(query) > -1) && (row.department.indexOf(query2) > -1) && (row.category.indexOf(query3) > -1)));
}
return array;
}
}
这样,如果用户使用某些name
进行搜索,则只会考虑具有非空值category
的行。
我也想考虑具有空值的行,但我无法这样做。
如果我将管道改为:
@Pipe({
name: "dataFilter"
})
export class DataFilterPipe implements PipeTransform {
transform(array: any[], query: string, query2: string, query3: string): any {
if (query || query2 || query3) {
return _.filter(array, row => ((row.name.indexOf(query) > -1) && (row.department.indexOf(query2) > -1) && (row.category.indexOf(query3) > -1)));
}
return array;
}
}
我收到错误:
Cannot read property 'indexOf' of null
非常感谢任何帮助。
答案 0 :(得分:0)
你需要检查每个row
的姓名,部门或者catigory是否为空:
@Pipe({
name: "dataFilter"
})
export class DataFilterPipe implements PipeTransform {
transform(array: any[], query: string,query2: string,query3: string): any {
if(query || query2 || query3)
{
return _.filter(array, row =>
{
var hasName = row.name && row.name.indexOf(query) > -1;
var hasDepartment = row.department && row.department.indexOf(query2) > -1
var hasCategory = row.category && row.category.indexOf(query3) > -1
return hasName && hasDepartment && hasCategory;
});
}
return array;
}
}
答案 1 :(得分:0)
试试这个,当我搜索多个列时,它对我来说很好。
transform(categories: any, searchText: any): any {
if(searchText == null) return categories;
return categories.filter(function(category){
var name_search=category.name.toLowerCase().indexOf(searchText.toLowerCase()) >
-1;
var email_search=category.email.toLowerCase().indexOf(searchText.toLowerCase())
> -1;
return name_search || email_search;
})
}
以前,当我使用这个&#34; import * as _ from&#34; lodash&#34;; &#34;也就是说,当我加载页面时数据没有显示,但是当我搜索数据时,过滤器工作正常,数据也显示..