如何使用Angular中的管道对表进行常规搜索? I have this working snippet,但i
的值仅为0
,我不知道为什么(因此,它只会在name
列中搜索我输入cc
不会找到任何内容。
如何修改代码以获得我想要的东西?谢谢您的时间!
filter.pipe.ts
transform(value: any, input: string) {
if (!value) {
return [];
}
if (!input) {
return value;
}
var valuesArr = []
if (input) {
input = input.toLowerCase();
return value.filter(function (el: any) {
valuesArr = Object.keys(el).map(key => el[key]);
for (var i in valuesArr) {
return valuesArr != null && valuesArr[i] != null && valuesArr[i] != undefined && valuesArr[i].toLowerCase().indexOf(input) > -1;
}
})
}
return value;
}
app.html
<input type="text" [(ngModel)]="toSearch" (click)="onClick(toSearch)">
<table>
<thead>
<tr>
<th>Name</th>
<th>Surname</th>
<th>Group</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let user of users | filter : toSearch">
<td>{{ user.name }}</td>
<td>{{ user.surname }}</td>
<td>{{ user.group }}</td>
<tr>
</tbody>
</table>
app.ts
toSearch
users = [
{name: "john", surname: "john1", group: null},
{name: "mike", surname: "", group: 'bb'},
{name: "anne", surname: "anne1", group: ''},
{name: "dan", surname: "dan1", group: 'cc'},
{name: "ben", surname: "", group: 'a'},
]
onClick(toSearch) {
this.toSearch = toSearch
}
答案 0 :(得分:4)
简单,只需检查您的匹配是否为真,然后通过
发送即可import { Pipe, PipeTransform, Injectable } from '@angular/core';
@Pipe({
name: 'filter',
})
@Injectable()
export class CheckBoxPipe implements PipeTransform {
transform(value: any, input: string) {
if (!value) {
return [];
}
if (!input) {
return value;
}
var values = []
if (input) {
input = input.toLowerCase();
return value.filter(function (el: any) {
values = Object.keys(el).map(key => el[key]);
let result = false;
for (var i in values) {
result = values != null && values[i] != null && values[i] != undefined && values[i].toLowerCase().indexOf(input) > -1;
if(result){
return true
}
}
return false;
})
}
return value;
}
}
答案 1 :(得分:1)
我还建议使用 ES6 运算符:
transform(value: any[], input: string) {
if (!value) {
return [];
}
if (!input) {
return value;
}
var valuesArr = []
if (input) {
console.log(input)
input = input.toLowerCase();
return value.filter( (el: any) => {
valuesArr = Object.keys(el).map(key => el[key]);
return valuesArr.some((elm)=> {
if (JSON.stringify(elm).includes(input)) {
return elm;
}
return null;
})
})
}
return value;
}