PrimeNG中根据p-selectButton选中状态过滤数组数据的方法
实现方法
- 核心原则:单独存储一份全量原始数组,所有过滤操作都基于原始数组生成新的展示数组,禁止直接修改原始数据,避免取消筛选时无法恢复全量内容。
- 给SelectButton组件绑定值变化事件,每次选中/取消选项时触发过滤逻辑,根据当前选中项动态生成要展示的数组。
- 页面所有用到该数组的位置,统一绑定过滤后的展示数组。
组件逻辑代码(TS)
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { // 全量原始数组,全程不修改 rawList = [ {"id":1,"active":1,"name":"paris"}, {"id":2,"active":0,"name":"london"}, {"id":3,"active":1,"name":"Australia"}, {"id":4,"active":0,"name":"india"} ]; // SelectButton绑定的选中值,对应原代码里的value2 value2: number[] = []; // 页面实际展示的过滤后数组 displayList = []; // SelectButton选项配置,对应原代码里的paymentOptions paymentOptions = [ { name: 'Option 1', value: 1 }, { name: 'Option 2', value: 2 } ]; ngOnInit() { // 初始化默认展示全量数据 this.displayList = [...this.rawList]; } // 筛选逻辑,选中值变化时触发 handleFilterChange(selected: number[]) { // 未选中任何选项,展示全量 if (selected.length === 0) { this.displayList = [...this.rawList]; return; } // 仅选中Option1:保留active=1的项 if (selected.includes(1) && !selected.includes(2)) { this.displayList = this.rawList.filter(item => item.active === 1); return; } // 仅选中Option2:保留active=0的项 if (selected.includes(2) && !selected.includes(1)) { this.displayList = this.rawList.filter(item => item.active === 0); return; } // 两个选项同时选中时默认展示全量,可根据业务需求调整过滤规则 this.displayList = [...this.rawList]; } }
模板代码(HTML)
<h5>Multiple Selection</h5> <p-selectButton [options]="paymentOptions" [(ngModel)]="value2" multiple="multiple" optionLabel="name" optionValue="value" (ngModelChange)="handleFilterChange($event)" ></p-selectButton> <!-- 数组展示区域示例,替换成实际业务渲染逻辑即可 --> <div class="list-wrap"> <div *ngFor="let item of displayList"> {{ item.name }} </div> </div>
补充说明
- 如果不需要支持两个选项同时选中的场景,可以删除
multiple="multiple"属性改为单选模式,过滤逻辑可以简化为直接判断单个选中值即可。 - 如果两个选项同时选中时有其他过滤规则(比如取交集、并集),直接修改
handleFilterChange方法里的filter判断条件即可。
内容的提问来源于stack exchange,提问作者Rinky Sharma
相关产品推荐
相关产品推荐

