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

Angular中如何使用mat-select-filter同时过滤两个属性?

实现多字段过滤(codigo + nombre)

要同时按编码(codigo)和名称(nombre)过滤,你可以利用mat-select-filter提供的自定义过滤函数(customFilter输入属性),替代默认的displayMember单字段过滤逻辑,具体步骤如下:

1. 修改模板代码

移除原有的[displayMember]属性,添加[customFilter]绑定到你将在组件中定义的过滤函数:

<mat-select-filter 
  [placeholder]="'Buscar..'" 
  [array]="estaciones" 
  [customFilter]="filterEstaciones"  <!-- 绑定自定义过滤函数 -->
  (filteredReturn)="filteredEstaciones = $event">
</mat-select-filter>
<mat-option *ngFor="let item of filteredEstaciones" [value]="item.id">
    {{ item.codigo }} - {{ item.nombre }}
</mat-option>

2. 在组件TypeScript中实现自定义过滤函数

在你的组件类里定义filterEstaciones函数,实现同时匹配codigo和nombre的逻辑(忽略大小写,兼容空输入):

import { Component } from '@angular/core';

@Component({
  // 组件元数据(省略)
})
export class YourComponent {
  estaciones: any[] = []; // 你的数据源
  filteredEstaciones: any[] = [];

  // 自定义过滤函数
  filterEstaciones(searchText: string, item: any): boolean {
    // 处理空输入:返回所有数据
    if (!searchText) return true;
    
    const lowerSearch = searchText.toLowerCase();
    // 判断编码或名称是否包含搜索文本
    return item.codigo.toLowerCase().includes(lowerSearch) 
        || item.nombre.toLowerCase().includes(lowerSearch);
  }
}

说明

  • customFilter会覆盖默认的单字段过滤逻辑,让你完全控制过滤规则
  • 函数接收两个参数:searchText是用户输入的过滤文本,item是数组中的每一项
  • 统一转成小写是为了实现不区分大小写的模糊匹配,你也可以根据需求调整为精确匹配

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 13:30:12