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

Angular技术问询:如何不使用Pipe实现输入框数组过滤

Angular中不使用Pipe实现输入框过滤数组内容

需求

在Angular项目中,不借助Pipe管道,通过输入框实时过滤数组内的字段内容。

原始数组结构

原始数组为乘客数据的字段定义,结构如下:

{
    "passengerId":"integer",
    "survived":"integer",
    "Pclass":"integer",
    "Name":"string",
    "Sex":"string",
    "Ticket":"string"
}

现有HTML模板代码

<div class="column-wrapper">
  <input type="text" placeholder="搜索" (keyup)="search($event)">
  <ul>
    <li *ngFor="let columnName of columnData">
      <input type="checkbox" name="" id="" [(ngModel)]="columnName.visible" [checked]="columnName">
      <p>{{columnName}}</p>
    </li>
  </ul>
</div>

现有TS组件代码

search($event:any){
  this.searchTerm = $event.target.value;
  this.filtered = this.columnData.filter((data:any) => data === this.searchTerm);
}

当前问题

当前过滤逻辑为严格相等匹配,只有输入内容与字段名完全一致时才会显示结果。例如输入“passenger”时,只能匹配到完全等于“passenger”的字段,但实际需要匹配包含该关键词的字段(如passengerId),当前无法实现这种模糊匹配。

修正方案

1. 调整TS过滤逻辑

修改search方法为大小写不敏感的模糊匹配,同时确保columnData是从原始对象提取的字段名数组:

// 初始化字段名数组
columnData: string[] = Object.keys({
    "passengerId":"integer",
    "survived":"integer",
    "Pclass":"integer",
    "Name":"string",
    "Sex":"string",
    "Ticket":"string"
});
filtered: string[] = [...this.columnData];
searchTerm: string = '';

search($event: any) {
  this.searchTerm = $event.target.value.trim().toLowerCase();
  // 模糊匹配:字段名包含搜索关键词(忽略大小写)
  this.filtered = this.columnData.filter(field => 
    field.toLowerCase().includes(this.searchTerm)
  );
}

2. 修正HTML模板

将*ngFor遍历对象改为filtered数组,确保显示过滤后的结果:

<div class="column-wrapper">
  <input type="text" placeholder="搜索" (keyup)="search($event)">
  <ul>
    <li *ngFor="let columnName of filtered">
      <input type="checkbox" [(ngModel)]="columnName.visible">
      <p>{{columnName}}</p>
    </li>
  </ul>
</div>

注:原模板中[checked]="columnName"存在逻辑错误,columnName为字符串无法作为布尔值判断;若需控制复选框状态,需将columnData改为包含visible属性的对象数组,而非单纯字符串数组。

修正后效果

输入“passenger”时,会匹配并显示passengerId字段;输入“Na”时,会匹配并显示Name字段,实现实时模糊过滤。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 02:05:32