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

Ionic中使用Pipe过滤器实现搜索栏时如何新增多个过滤字段

实现方案

修正后完整Pipe代码

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

@Pipe({
  name: 'filter'
})
export class FilterPipe implements PipeTransform {
  // 修正search参数类型,ion-searchbar绑定的值为字符串类型
  transform(nomes: any[], search: string): any[] {
    // 搜索关键词为空直接返回原数组
    if (!search) return nomes;
    // 统一转为小写实现不区分大小写匹配,不需要可去掉toLowerCase
    const searchStr = search.toLowerCase();
    return nomes.filter(nome => {
      // 三个字段任意一个匹配即命中
      return (
        nome?.titulo?.toLowerCase().includes(searchStr) ||
        nome?.city?.toLowerCase().includes(searchStr) ||
        String(nome?.age).toLowerCase().includes(searchStr)
      );
    });
  }
}

逻辑说明

  • 修复了原代码中search参数的类型错误,原代码误写为数组类型,实际从搜索框绑定的值为字符串类型
  • 所有字段都用可选链?.做空值保护,避免字段不存在时报错
  • 数字类型的age先转为字符串再做包含匹配,如果需要精确匹配年龄,可将对应判断逻辑改为nome?.age === Number(search)
  • 默认实现了不区分大小写的搜索,不需要该特性可以删除所有toLowerCase()调用

HTML部分无需修改

原HTML代码可以正常使用,只需确保对应组件中声明的search变量为字符串类型即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 05:24:06