You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过搜索框输入内容过滤Angular中*ngFor的渲染结果

实现Angular中*ngFor全局搜索过滤的方案

第一步:配置双向绑定依赖

首先在对应功能模块/根模块导入FormsModule,开启ngModel双向绑定支持,同时后续要把自定义过滤管道声明到模块中:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { FilterPipe } from './filter.pipe';
// 你已有的reverse管道也照常导入声明即可

@NgModule({
  declarations: [
    AppComponent,
    FilterPipe
  ],
  imports: [
    BrowserModule,
    FormsModule
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

第二步:绑定搜索关键词

在你的组件类中声明搜索关键词变量:

searchKeyword: string = '';

修改搜索框模板,绑定双向数据:

<input type="text" [(ngModel)]="searchKeyword" placeholder="输入内容搜索">

第三步:创建自定义过滤管道

新建filter.pipe.ts文件,实现和AngularJS默认filter一致的全字段匹配逻辑:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'filter'
})
export class FilterPipe implements PipeTransform {
  transform(items: any[], keyword: string): any[] {
    // 无数据/无搜索词时直接返回原数组
    if (!items || !keyword?.trim()) {
      return items;
    }
    const lowerKeyword = keyword.trim().toLowerCase();
    // 遍历数组,匹配对象所有属性的值,只要有一个匹配就保留
    return items.filter(item => {
      return Object.values(item).some(val => 
        String(val).toLowerCase().includes(lowerKeyword)
      );
    });
  }
}

如果遇到数组引用未更新导致过滤不生效的场景,可以在@Pipe配置中加pure: false,该配置会提升更新频率但会增加性能开销,非必要不开启。

第四步:修改*ngFor管道链

把过滤管道插入到async之后、reverse之前,传入绑定的搜索关键词即可:

<input type="text" [(ngModel)]="searchKeyword" placeholder="输入内容搜索">
<article *ngFor="let x of y | async | filter: searchKeyword | reverse">
    <p>Name: {{x.firstName}} {{x.secondName}}, City: {{x.city}}, Phone: {{x.phone}}</p>
</article>

如果你需要限定只搜索指定字段,修改过滤管道中匹配逻辑,只判断firstName/city/phone等对应属性即可。

内容的提问来源于stack exchange,提问作者Alex

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.08 13:36:05