Angular中使用gridApi.getFilterInstance实现自定义搜索框同时检索firstname和lastname列
实现方案
原有HTML代码无需修改,仍然绑定同一个onSearch方法即可,逻辑部分有两种常用实现方式:
方案1:使用ag-grid外部过滤器(推荐,适配多列任意匹配场景)
该方案逻辑灵活易维护,不需要单独操作每列的过滤器实例:
- 先在gridOptions中配置外部过滤器回调
// 组件初始化阶段配置gridOptions this.gridOptions = { // 保留你原有的其他grid配置 isExternalFilterPresent: () => { // 搜索框有值时触发外部过滤 return !!this.form.value?.text?.trim(); }, doesExternalFilterPass: (node) => { const searchKey = this.form.value.text.trim().toLowerCase(); const firstName = node.data?.contact?.firstName?.toLowerCase() || ''; const lastName = node.data?.contact?.lastName?.toLowerCase() || ''; // 规则:firstName或lastName任意一个以搜索关键词开头即匹配 return firstName.startsWith(searchKey) || lastName.startsWith(searchKey); } }
- 简化onSearch方法
onSearch() { this.reportTable.gridApi.onFilterChanged(); }
后续如果需要调整匹配规则(比如改成包含匹配、新增更多检索列),仅需修改doesExternalFilterPass中的判断逻辑即可。
方案2:通过列过滤器+全局OR逻辑实现
如果需要保留原列过滤器的交互能力,可以用该方案:
onSearch() { const filter = this.form.value['text']?.trim(); // 搜索词为空时清空所有过滤器 if (!filter) { this.reportTable.gridApi.setFilterModel(null); this.reportTable.gridApi.onFilterChanged(); return; } // 构造两列的过滤条件 const filterModel = { 'contact.firstName': { filterType: 'text', type: 'startsWith', filter: filter }, 'contact.lastName': { filterType: 'text', type: 'startsWith', filter: filter } }; // 应用过滤模型,设置多列匹配逻辑为OR(任意一列匹配即可) this.reportTable.gridApi.setFilterModel(filterModel); this.reportTable.gridApi.setFilterModelOperator('OR'); this.reportTable.gridApi.onFilterChanged(); }
注意:如果你的ag-grid版本低于23.0.0,不支持setFilterModelOperator方法,必须使用方案1实现多列OR匹配逻辑。
内容的提问来源于stack exchange,提问作者Aman Sharma
相关产品推荐
相关产品推荐

