我拥有所有商家信息屏幕的数据表。现在我需要将过滤器选项更改为泛型,如单个文本字段,以过滤整个数据表。我的代码如下所示, 在查看文件中:
<div class="col-sm-3">
<input class="form-control" [(ngModel)]="filterQuery" />
</div>
<div class="panel panel-default">
<table class="table table-striped"
[mfData]="data | dataFilter : filterQuery" #mf="mfDataTable"
[mfRowsOnPage]="rowsOnPage" [(mfSortBy)]="sortBy"
[(mfSortOrder)]="sortOrder">
<thead>
<tr>
<th style="width: 10%" class="text-center"><mfDefaultSorter by="id_category">Id</mfDefaultSorter></th>
<th style="width: 30%" class="text-center"><mfDefaultSorter
by="name">Name</mfDefaultSorter></th>
<th style="width: 30%" class="text-center"><mfDefaultSorter
by="category_code">Code</mfDefaultSorter></th>
<th style="width: 10%" class="text-center"><mfDefaultSorter
by="status">Status</mfDefaultSorter></th>
<th style="width: 20%" class="text-center">Option</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let item of mf.data">
....
</tr>
</tbody>
</table>
</div>
我在过滤器代码中遇到问题,它没有按照给定的字符串进行过滤。我可以对单列进行过滤,但我需要对所有列进行过滤,它应该适用于任何数据数组对象。我的过滤器代码如下所示,
@Pipe( {
name: 'dataFilter'
} )
export class DataFilterPipe implements PipeTransform {
transform( valueArray: any, term: any ) {
if ( term ) {
let filterKeys = Object.keys( valueArray[0] );
return valueArray.filter(( item: any ) =>
filterKeys.reduce(( memo, keyName ) =>
memo && item[keyName].toLowerCase().indexOf( term.toLowerCase() ) > -1, true ) );
} else {
return valueArray;
}
}
}
答案 0 :(得分:0)
I think you want something like this:
export class DataFilterPipe implements PipeTransform {
transform(array: Array<any>, value: string) {
if (value && array) {
return array.filter((item: any) => this.matchAnyKey(value, item));
} else {
return array;
}
}
matchAnyKey(value: string, obj: any): boolean {
let filterKeys = Object.keys(obj);
let matchedProps = filterKeys.filter(key => obj[key]
&& typeof obj[key] === 'string'
&& obj[key].toLowerCase().indexOf(value.toLowerCase()) > -1);
return matchedProps.length > 0;
}
}