如何使用输入字段过滤Angular 4中*ngFor循环内的项目

Ris*_*wal 4 angular

我想基于字符串中存在特定子字符串的事实来过滤Angular 4中的ngFor循环中的项目

对于Ex:

agents[] = [
  { id: 11, name: 'Agent 0', email:'admin@ab.com' },
  { id: 12, name: 'Agent 1', email:'admin@ab.com'},
  { id: 13, name: 'Agent 2', email:'admin@ab.com' },
  { id: 14, name: 'Agent 3', email:'admin@ab.com' },
  { id: 15, name: 'Agent 4', email:'admin@ab.com' },
  { id: 16, name: 'Agent 5', email:'admin@ab.com' },
  { id: 17, name: 'Agent 6', email:'admin@ab.com' },
  { id: 18, name: 'Agent 7', email:'admin@ab.com' },
  { id: 19, name: 'Agent 8', email:'admin@ab.com' },
  { id: 20, name: 'Agent 9', email:'admin@ab.com' }
];
Run Code Online (Sandbox Code Playgroud)

在名称中搜索

搜索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>
Run Code Online (Sandbox Code Playgroud)

agent.component.ts

values = '';
ab = '';
 onagentKey(event: any) { 
     this.values = event.target.value;
   this.ab = this.values;

  }
Run Code Online (Sandbox Code Playgroud)

所以任何人都可以告诉我什么以及如何使用过滤器,管道或任何其他东西来解决这个问题

感谢提前

小智 9

我的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;
    }
}
Run Code Online (Sandbox Code Playgroud)

并在您的HTML中

<input type="text" [(ngModel)]="query">
<div *ngFor="let agent of agents | fullTextSearch:query:'name'"><!-- ... --></div>
Run Code Online (Sandbox Code Playgroud)

如果您需要帮助来阅读代码,请随时提出