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

Angular 14中Material表格单列过滤及搜索触发函数实现问题

Angular 14 Material表格单列过滤(点击搜索按钮触发)

1. 修改模板代码

给mat-input添加模板引用变量,在mat-form-field内嵌入搜索按钮,点击时直接传入输入框的值到过滤函数:

<mat-form-field appearance="fill">
  <mat-label>搜索</mat-label>
  <!-- 添加#searchInput模板引用,用于快速获取输入值 -->
  <input #searchInput matInput placeholder="输入关键词">
  <!-- 搜索按钮,点击时调用FilterChange并传入输入框内容 -->
  <button mat-icon-button matSuffix (click)="FilterChange(searchInput.value)">
    <mat-icon>search</mat-icon>
  </button>
</mat-form-field>

<!-- 你的Material表格结构(示例) -->
<table mat-table [dataSource]="dataSource">
  <ng-container matColumnDef="name">
    <th mat-header-cell *matHeaderCellDef> 姓名 </th>
    <td mat-cell *matCellDef="let element"> {{element.name}} </td>
  </ng-container>
  <!-- 其他列定义请根据实际业务调整 -->
  
  <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
  <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>

2. 调整组件逻辑

修改FilterChange函数适配传入的参数,同时配置filterPredicate实现单列过滤(默认是全局所有列匹配,需自定义规则指定目标列):

import { Component, OnInit } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';

// 替换成你的实际数据接口
interface TableData {
  id: number;
  name: string;
  // 其他字段...
}

@Component({
  selector: 'app-your-component',
  templateUrl: './your-component.component.html',
  styleUrls: ['./your-component.component.css']
})
export class YourComponent implements OnInit {
  // 表格列名(根据实际列调整)
  displayedColumns: string[] = ['name'];
  // 表格数据源
  dataSource = new MatTableDataSource<TableData>([]);

  ngOnInit(): void {
    // 配置单列过滤规则:只匹配name列(替换成你需要过滤的列名)
    this.dataSource.filterPredicate = (data: TableData, filter: string) => {
      // 忽略大小写,判断关键词是否在目标列中
      return data.name.toLowerCase().includes(filter.toLowerCase());
    };
  }

  // 调整函数参数为输入值,直接用于过滤
  FilterChange(filterValue: string) {
    // 去除首尾空格并统一转小写,保证过滤的一致性
    this.dataSource.filter = filterValue.trim().toLowerCase();
  }
}

关键说明

  • 模板引用变量#searchInput可以直接获取输入框的当前值,不用通过event解析,代码更简洁。
  • filterPredicate是Material表格数据源的核心配置,通过它可以自定义过滤逻辑,这里指定只对name列进行匹配,实现单列过滤效果。
  • 过滤时统一处理大小写和空格,避免因大小写敏感或无效空格导致的匹配失效问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 09:30:52