如何通过选择下拉框值实现Angular表格数据的筛选
Angular表格多下拉筛选实现方案
核心思路
保留原始全量数据源不修改,单独维护筛选后的数组用于表格渲染,每次下拉框选中值变化时,根据所有选中的筛选条件对全量数据做交集过滤,未选中的筛选项默认不做限制。
1. 组件TS代码示例
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-demo-table', templateUrl: './demo-table.component.html', styleUrls: ['./demo-table.component.css'] }) export class DemoTableComponent implements OnInit { // 原始全量数据,永远不修改,只作为过滤源 demoList = [ { name:"asian003", model:"hyper20", class:"selina0127" }, { name:"asian003", model:"hyper21", class:"selina0127" }, { name:"norva", model:"hyper21", class:"gowri.14" }, { name:"sparks007", model:"NNc22", class:"gowri.14" }, { name:"asian003", model:"NNc22", class:"selina0127" } ]; // 筛选后的数据,用于表格渲染 filteredList = [...this.demoList]; // 下拉框选中值,默认空代表不筛选该字段 selectedName: string = ''; selectedModel: string = ''; selectedClass: string = ''; // 下拉框可选值,初始化时去重生成 nameOptions: string[] = []; modelOptions: string[] = []; classOptions: string[] = []; ngOnInit(): void { // 生成各字段去重后的下拉可选值 this.nameOptions = [...new Set(this.demoList.map(item => item.name))]; this.modelOptions = [...new Set(this.demoList.map(item => item.model))]; this.classOptions = [...new Set(this.demoList.map(item => item.class))]; } // 筛选逻辑 filterTable(): void { this.filteredList = this.demoList.filter(item => { // 每个筛选项有值就匹配,没值就直接返回true跳过该条件 const nameMatch = this.selectedName ? item.name === this.selectedName : true; const modelMatch = this.selectedModel ? item.model === this.selectedModel : true; const classMatch = this.selectedClass ? item.class === this.selectedClass : true; // 同时满足所有生效的筛选条件才保留 return nameMatch && modelMatch && classMatch; }); } }
2. 模板HTML代码示例
<!-- 筛选下拉框区域 --> <div style="margin-bottom: 16px; display: flex; gap: 16px;"> <div> <label>Name筛选:</label> <select [(ngModel)]="selectedName" (change)="filterTable()"> <option value="">全部</option> <option *ngFor="let name of nameOptions" [value]="name">{{name}}</option> </select> </div> <div> <label>Model筛选:</label> <select [(ngModel)]="selectedModel" (change)="filterTable()"> <option value="">全部</option> <option *ngFor="let model of modelOptions" [value]="model">{{model}}</option> </select> </div> <div> <label>Class筛选:</label> <select [(ngModel)]="selectedClass" (change)="filterTable()"> <option value="">全部</option> <option *ngFor="let className of classOptions" [value]="className">{{className}}</option> </select> </div> </div> <!-- 表格渲染区域,遍历筛选后的数组 --> <table border="1" cellpadding="8" cellspacing="0"> <thead> <tr> <th>Name</th> <th>Model</th> <th>Class</th> </tr> </thead> <tbody> <tr *ngFor="let item of filteredList"> <td>{{item.name}}</td> <td>{{item.model}}</td> <td>{{item.class}}</td> </tr> </tbody> </table>
注意事项
- 确保你的Angular模块已经导入了
FormsModule,否则[(ngModel)]双向绑定会失效 - 如果你的数据是异步请求获取的,需要在数据返回后再初始化下拉可选值和初始筛选数组
内容的提问来源于stack exchange,提问作者Jay
相关产品推荐
相关产品推荐

