Angular Ag-Grid刷新数据:关闭芯片恢复默认状态及多筛选实现求助
解决ag-grid结合Angular Material芯片的多筛选与重置问题
我来帮你搞定这个ag-grid结合Angular Material芯片的多筛选和重置问题!核心思路是维护原始数据副本、用数组管理活跃筛选条件,再通过自定义过滤逻辑实现多条件筛选和重置,具体步骤如下:
1. 核心状态管理
首先在组件里维护三个关键变量,分别存储原始数据、过滤后的数据,以及当前活跃的筛选关键词(对应芯片内容):
// 从JSON加载的原始数据(深拷贝避免被修改) originalGridData: any[] = []; // 绑定给ag-grid的过滤后数据源 filteredGridData: any[] = []; // 存储当前所有活跃的筛选关键词 activeFilters: string[] = []; // 搜索输入框的双向绑定值 searchKeyword: string = '';
2. 初始化加载原始数据
从JSON文件加载数据时,一定要深拷贝原始数据,这样后续重置时才能准确回到初始状态:
loadGridData() { this.http.get('assets/your-grid-data.json').subscribe((data: any[]) => { // 深拷贝原始数据,防止后续过滤修改原数据 this.originalGridData = JSON.parse(JSON.stringify(data)); // 初始化过滤后数据为原始数据 this.filteredGridData = [...this.originalGridData]; }); }
3. 实现多筛选逻辑
写一个核心的过滤函数,根据activeFilters数组里的所有关键词,对原始数据进行多条件匹配(这里默认是或逻辑:只要行数据的任意字段包含任意一个关键词就保留,你可以根据需求改成与逻辑):
applyFilters() { // 如果没有活跃筛选条件,直接重置为原始数据 if (this.activeFilters.length === 0) { this.filteredGridData = [...this.originalGridData]; return; } // 多条件过滤逻辑 this.filteredGridData = this.originalGridData.filter(row => { // 遍历行的所有字段值 return Object.values(row).some(cellValue => { // 转成字符串并忽略大小写,判断是否包含任意一个筛选关键词 return this.activeFilters.some(filter => cellValue.toString().toLowerCase().includes(filter.toLowerCase()) ); }); }); }
4. 搜索与芯片交互
- 点击搜索按钮时,把输入的关键词添加到
activeFilters数组,清空输入框并触发过滤:
onSearch() { const trimmedKeyword = this.searchKeyword.trim(); // 避免重复添加空值或已存在的关键词 if (trimmedKeyword && !this.activeFilters.includes(trimmedKeyword)) { this.activeFilters.push(trimmedKeyword); this.searchKeyword = ''; this.applyFilters(); } }
- 点击芯片的“X”按钮时,移除对应关键词并重新应用过滤:
removeFilter(filter: string) { const filterIndex = this.activeFilters.indexOf(filter); if (filterIndex !== -1) { this.activeFilters.splice(filterIndex, 1); this.applyFilters(); } }
5. 模板部分调整
把搜索框、芯片列表和ag-grid绑定起来,注意ag-grid的rowData要绑定到filteredGridData:
<!-- 外部搜索输入框 --> <mat-form-field appearance="fill"> <mat-label>搜索关键词</mat-label> <input matInput [(ngModel)]="searchKeyword" (keyup.enter)="onSearch()"> <button mat-icon-button matSuffix (click)="onSearch()"> <mat-icon>search</mat-icon> </button> </mat-form-field> <!-- 筛选芯片列表 --> <mat-chip-listbox class="filter-chips"> <mat-chip *ngFor="let filter of activeFilters" removable (removed)="removeFilter(filter)"> {{ filter }} <button matChipRemove aria-label="移除筛选条件"> <mat-icon>cancel</mat-icon> </button> </mat-chip> </mat-chip-listbox> <!-- ag-grid 组件 --> <ag-grid-angular style="width: 100%; height: 600px;" class="ag-theme-alpine" [rowData]="filteredGridData" [columnDefs]="yourColumnDefs" <!-- 这里可以去掉原有的quickFilterText绑定,因为我们自己控制数据源过滤 --> ></ag-grid-angular>
关键注意事项
- 深拷贝原始数据:一定要确保
originalGridData是原始数据的深拷贝,避免过滤时修改原数据导致重置失败。 - 筛选逻辑灵活调整:如果需要针对特定字段筛选,或者改成“所有关键词都匹配”的与逻辑,只需要修改
applyFilters里的判断逻辑即可。 - 避免重复筛选:添加芯片时要检查关键词是否已存在,防止重复添加相同的筛选条件。
内容的提问来源于stack exchange,提问作者Deepanshu Kaushik
相关产品推荐
相关产品推荐

