我想基于字符串中是否存在特定子字符串的事实来过滤Angular 4中ngFor循环中的项目
例如:
agents[] = [
{ id: 11, name: 'Agent 0', email:'[email protected]' },
{ id: 12, name: 'Agent 1', email:'[email protected]'},
{ id: 13, name: 'Agent 2', email:'[email protected]' },
{ id: 14, name: 'Agent 3', email:'[email protected]' },
{ id: 15, name: 'Agent 4', email:'[email protected]' },
{ id: 16, name: 'Agent 5', email:'[email protected]' },
{ id: 17, name: 'Agent 6', email:'[email protected]' },
{ id: 18, name: 'Agent 7', email:'[email protected]' },
{ id: 19, name: 'Agent 8', email:'[email protected]' },
{ id: 20, name: 'Agent 9', email:'[email protected]' }
];
搜索名称
搜索0时仅显示代理0,搜索1时仅显示代理1搜索“ a”,“ g”,“ e”,“ n”,“ t”,“”等时显示全部代理。
我设法在{{ab}}的文本框中保存了输入
即
agent.component.html
<input (keyup)="onagentKey($event)" class="form-control input-lg" type="text" placeholder="Find a Agent....">
<div *ngFor = "let agent of agents" class="col-sm-4">Name : {{agent.name}}<br>
Email : {{agent.email}}
</div>
agent.component.ts
values = '';
ab = '';
onagentKey(event: any) {
this.values = event.target.value;
this.ab = this.values;
}
所以谁能告诉我什么以及如何使用过滤器,管道或其他任何东西来解决这个问题
预先感谢
我的faovrite解决方案是使用管道:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'fullTextSearch',
pure: false
})
export class FullTextSearchPipe implements PipeTransform {
constructor() { }
transform(value: any, query: string, field: string): any {
return query ? value.reduce((prev, next) => {
if (next[field].includes(query)) { prev.push(next); }
return prev;
}, []) : value;
}
}
在您的HTML中
<input type="text" [(ngModel)]="query">
<div *ngFor="let agent of agents | fullTextSearch:query:'name'"><!-- ... --></div>
如果您需要帮助来阅读代码,请随时询问
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句