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

瑞沙(Rishabh Agrawal)

我想基于字符串中是否存在特定子字符串的事实来过滤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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何根据对象属性字符串过滤“ ngFor”循环中的项目

如何清除Angular中过滤的输入字段?

Angular 8项目,我无法在json对象中获取值以显示在ngFor循环中的模板上

如何使用angular4在ngFor循环中显示嵌套的@component?

如何使用Angular 4在ngFor循环中渲染多个ng-content?

根据 Angular 4 中的变量在 *ngFor 循环中修改 HTML 标签

如何从嵌套的 ngFor 循环中的离子选择中获取价值?

如何使用 AngularJS 2/4 在 ngFor 循环中动态使用模型变量?

在ngFor循环中编辑项目时如何阻止所有项目打开

在 angular 中,我们如何在 ngFor 循环中定义的 ngIf 中使用局部变量?

如何使用 Angular 7 中的模块有条件地绑定 ngFor 循环中的类或属性值?

对 *ngFor 中的每个项目使用 for 循环和本地数组

如何安全地从for循环中的数组中删除项目?

如果返回错误,如何跳过 R 中循环中的项目?

如何在循环中从int的HashSet列表中删除项目

使用Angular 8在NgFor循环中将项目标记为已更新

如何在Angular 4中摆脱* ngFor循环?

使用“next”方法跳过 Ruby 中 .each 循环中的项目

使用for循环中的拼接从数组中删除项目

Angular-如何在ngFor循环中使用“此”项目的布尔值隐藏和显示内容

在ionic2 / angular2项目中的* ngFor循环中呈现html内容

如何更改ngFor循环中每个项目的相同HTML元素的内容(有延迟)?

*ngFor 循环中多个输入文件的问题

使用ngif ionic4过滤ngfor中的json数据

在输入字段中输入内容时如何过滤列表?

如何使用react和javascript根据输入字段中的值过滤数据?

如何使用数组中的项目数在 PHP 循环中逐渐接近 1.0 的值

如何使用* ngFor过滤Angular中未知数量的元素?

如何连接循环中的项目