ag-grid-angular中实现列唯一值下拉过滤器的方法求助
在ag-grid-angular中实现下拉式列过滤器(基于列唯一值)
1. 创建自定义下拉过滤器组件
生成Angular组件并实现IFilterAngularComp接口,完成过滤器核心逻辑:
dropdown-filter.component.ts
import { Component, OnInit } from '@angular/core'; import { IFilterAngularComp, IDoesFilterPassParams, IFilterParams } from 'ag-grid-angular'; @Component({ selector: 'app-dropdown-filter', templateUrl: './dropdown-filter.component.html', styleUrls: ['./dropdown-filter.component.scss'] }) export class DropdownFilterComponent implements IFilterAngularComp, OnInit { params!: IFilterParams; filterValue: string | null = null; uniqueOptions: string[] = []; agInit(params: IFilterParams): void { this.params = params; } ngOnInit(): void { this.getUniqueColumnValues(); } // 提取当前列的所有唯一值 getUniqueColumnValues(): void { const rowData = this.params.api?.getRowData() || []; const field = this.params.colDef.field; // 去重并过滤空值 this.uniqueOptions = Array.from(new Set(rowData.map(row => row[field]).filter(val => val != null))); // 添加"全部"选项用于清空过滤 this.uniqueOptions.unshift('全部'); } // 判断过滤器是否激活 isFilterActive(): boolean { return this.filterValue != null && this.filterValue !== '全部'; } // 校验行数据是否符合过滤条件 doesFilterPass(params: IDoesFilterPassParams): boolean { if (!this.isFilterActive()) return true; const rowValue = params.data[this.params.colDef.field]; return rowValue === this.filterValue; } // 获取过滤模型(用于保存/恢复过滤状态) getModel(): any { return this.isFilterActive() ? { value: this.filterValue } : null; } // 设置过滤模型 setModel(model: any): void { this.filterValue = model?.value || '全部'; } // 下拉选项变更时触发过滤 onFilterChange(event: Event): void { const target = event.target as HTMLSelectElement; this.filterValue = target.value; this.params.filterChangedCallback(); } }
dropdown-filter.component.html
<select [(ngModel)]="filterValue" (change)="onFilterChange($event)" class="ag-filter-select"> <option *ngFor="let option of uniqueOptions" [value]="option">{{ option }}</option> </select>
2. 配置Angular模块
将自定义组件声明在对应模块中,旧版ag-grid(v24及以前)需添加到entryComponents:
import { NgModule } from '@angular/core'; import { AgGridModule } from 'ag-grid-angular'; import { DropdownFilterComponent } from './dropdown-filter.component'; @NgModule({ declarations: [DropdownFilterComponent], imports: [AgGridModule], // 新版ag-grid无需entryComponents entryComponents: [DropdownFilterComponent] }) export class YourFeatureModule { }
3. 在列定义中启用自定义过滤器
在表格列配置里指定使用该过滤器:
columnDefs = [ { headerName: '目标列名', field: 'targetField', filter: DropdownFilterComponent, // 可选:传递自定义参数 filterParams: { // 如:placeholder: '请选择' } }, // 其他列配置... ];
补充说明
- 若表格数据异步加载,可在数据加载完成后调用
gridApi.refreshHeader()刷新过滤器选项:onGridReady(params: any): void { this.gridApi = params.api; // 数据加载完成后执行 this.gridApi.refreshHeader(); } - 可根据列数据类型(数字、日期等)调整
getUniqueColumnValues的类型处理逻辑; - 自定义下拉框样式可匹配ag-grid默认风格,避免视觉差异。
内容的提问来源于stack exchange,提问作者Yatharth Nigam
相关产品推荐
相关产品推荐

