如何实现带有搜索框的自定义列头的Ag-grid表格?
实现Ag-Grid自定义列头带搜索框的方案
要实现列头文本下方带搜索框的Ag-Grid表格,核心是利用Ag-Grid的自定义列头组件能力,结合内置的过滤API完成搜索逻辑,具体实现步骤如下:
1. 自定义列头组件
以React为例,编写包含列名和搜索框的自定义组件,同时实现输入触发过滤的逻辑:
import { useState } from 'react'; const CustomHeader = (props) => { const [searchText, setSearchText] = useState(''); const handleSearch = (e) => { const inputValue = e.target.value; setSearchText(inputValue); // 调用Ag-Grid API设置当前列的过滤规则 props.api.setFilterModel({ [props.colDef.field]: { filterType: 'text', filter: inputValue, type: 'contains' // 可选规则:equals、startsWith、endsWith等 } }); }; return ( <div className="custom-header"> <span>{props.displayName}</span> <input type="text" placeholder="搜索..." value={searchText} onChange={handleSearch} className="header-search-input" /> </div> ); };
2. 配置列定义
在列配置中,为需要添加搜索框的列指定headerComponent为自定义组件,并开启列过滤:
const columnDefs = [ { field: 'name', headerName: '姓名', headerComponent: CustomHeader, filter: true // 必须开启,否则过滤逻辑不生效 }, { field: 'age', headerName: '年龄', headerComponent: CustomHeader, filter: true }, // 其他列配置... ];
3. 开启表格过滤功能
在Grid配置中全局启用过滤:
const gridOptions = { columnDefs, rowData: yourRowData, enableFilter: true, // 全局开启过滤 // 其他Grid配置... };
4. 样式调整
添加CSS使列头布局符合需求:
.custom-header { display: flex; flex-direction: column; align-items: center; padding: 4px 0; } .header-search-input { width: 90%; margin-top: 4px; padding: 2px 6px; font-size: 12px; border: 1px solid #e0e0e0; border-radius: 3px; }
其他框架适配说明
- Vue:通过
<template>定义自定义列头组件,在列配置中指定headerComponent: 'custom-header',并在组件内调用Grid API实现过滤。 - Angular:创建独立的组件作为列头,通过
headerComponent绑定,逻辑与React一致。
内容的提问来源于stack exchange,提问作者Sharads kumar
相关产品推荐
相关产品推荐

