【问题标题】:Filter *ngFor results from a search box input从搜索框输入过滤 *ngFor 结果
【发布时间】:2021-10-15 01:42:59
【问题描述】:

我正在寻找一种简单的方法来过滤来自搜索框输入的 *ngFor 结果。与 AngularJS 中的方法相同:ng-model="searchBox" / ng-repeat="x in y | filter:searchBox"...

我的代码是:

<input type="text">
<article *ngFor="let x of y | async | reverse">
    <p>Name: {{x.firstName}} {{x.secondName}}, City: {{x.city}}, Phone: {{x.phone}}</p>
</article>

【问题讨论】:

  • 您的意思是像自定义过滤器?如果是这样,也许这会有所帮助stackoverflow.com/questions/34164413/…
  • 我的目标有点不同 - 当您在输入中写入“a”时,应显示其值中包含“a”的每个对象。

标签: angular filter ngfor


【解决方案1】:

最简单的方法是使用*ngIf 过滤您的结果,而无需自定义pipe,您的代码如下所示

<input type="text">
<article *ngFor="let x of y | async | reverse">
  <p *ngIf="x.param == yourFilteredValue">Name: {{x.firstName}} {{x.secondName}}, City: {{x.city}}, Phone: {{x.phone}}</p>
</article>

或者你可以用 div 包裹你的整个 article 主体,并带有 *ngIf 表达式。

【讨论】:

  • 这种解决方案很有效,但想法是对象中是否有值“London”并且您编写“Lon”以显示它。使用“==”,仅当您在输入中输入完整的“伦敦”时才会显示...
  • @Alex - 在您的参数上尝试.startsWith(yourFilteredValue)。它应该是这样的:*ngIf="x.param.startsWith(yourValue)"
  • 谢谢,我将您的示例与包含()一起使用,它完成了工作!不幸的是,由于我的声誉,我无法投票。 :)
  • @Alex - 太棒了!很高兴知道这在某种程度上有所帮助。
【解决方案2】:

您也可以尝试将过滤器逻辑保留在 ts 文件中,然后返回一个包含所需项目的数组。然后你可以循环它们并根据需要显示。

【讨论】:

    【解决方案3】:

    在模板中

      <input type="text" [(ngModel)]="searchItem">
      <div *ngIf="(data$| async)?.length;" >
        <article *ngFor="let x of y | async | myFilter: searchItem">
         <p>Name: {{x.firstName}} {{x.secondName}}, City: {{x.city}}, Phone 
          {{x.phone}}</p>
        </article>
     ​</div>
    

    自定义管道

     transform(value: any[], ...args: any): any {
        let searchItem = ''
        if(args.length)  searchItem = args[0].toLowerCase()
        return value.filter((data:any)=> data.firstName.toLowerCase().includes(searchItem));
      }
    

    您可以更改键 (data.firstName) 以匹配您想要过滤的任何内容。

    【讨论】:

      猜你喜欢
      • 2012-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-02
      • 2012-07-05
      • 2017-05-17
      • 1970-01-01
      相关资源
      最近更新 更多