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

Angular如何使用pipe和map实现表单输入筛选匹配客户名称功能

Angular 表单筛选可观察对象数据实现方案

前置修复:修正FoundValues类的语法和逻辑错误

你现有FoundValues类存在参数名错误、变量冲突、匹配逻辑倒置的问题,先修复为如下代码:

export class FoundValues {
    customerName: string;
    startDate: string;
    endDate: string;

    includes(searchValue: string) : boolean {
      const lowerSearch = searchValue.toLowerCase();
      return this.valueIncludes(this.customerName, lowerSearch);
    }

    private valueIncludes(targetValue: string, searchValue: string){
       if (targetValue && searchValue) {
         return targetValue.toLowerCase().includes(searchValue);
       }
       return false;
    }
}

export interface MyInterface {
    found_values : Array<FoundValues>;
}

组件逻辑实现

第一步:导入依赖的rxjs操作符

import { combineLatest } from 'rxjs';
import { map, startWith } from 'rxjs/operators';

第二步:修正组件变量声明和筛选逻辑

你之前报错的核心原因是没有关联原始可观察数据源myData$和表单输入流,且变量类型声明错误,修改后组件代码如下:

export class MyComponent implements OnInit{
      // 修正myData$的类型注解写法,不是赋值
      myData$: Observable<MyInterface>;
      myControl = new FormControl();
      // 声明筛选结果的可观察类型
      filterData$: Observable<FoundValues[]>;

     ngOnInit(): void{
        // 组合原始数据流和表单输入流,任意流更新都会重新触发筛选
        this.filterData$ = combineLatest([
          this.myData$,
          // 给表单输入加初始空值,保证页面加载时就渲染全部数据
          this.myControl.valueChanges.pipe(startWith(''))
        ]).pipe(
          map(([originData, searchKey]) => this._filter(originData.found_values, searchKey))
        );
     }

     private _filter(dataList: FoundValues[], searchKey: string): FoundValues[]{
         // 搜索关键词为空时返回全部数据
         if(!searchKey?.trim()) return dataList;
         const formatKey = searchKey.trim().toLowerCase();
         // 匹配客户名称
         return dataList.filter(item => item.includes(formatKey));
     }
}

模板渲染

在模板中通过async管道直接订阅筛选结果流即可:

<input type="text" [formControl]="myControl" placeholder="输入客户名称搜索">
<ul>
  <li *ngFor="let item of filterData$ | async">
    客户名称:{{item.customerName}},起止日期:{{item.startDate}} ~ {{item.endDate}}
  </li>
</ul>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 22:36:05