I have a array as follows -
[
{
"id":1,
"active":1,
"name":"paris"
},
{
"id":2,
"active":0,
"name":"london"
},
{
"id":3,
"active":1,
"name":"Australia"
},
{
"id":4,
"active":0,
"name":"india"
}
]
I have a select button as follows:
code -
<h5>Multiple Selection</h5>
<p-selectButton
[options]="paymentOptions"
[(ngModel)]="value2"
multiple="multiple"
optionLabel="name"
optionValue="value"
></p-selectButton>
component -
this.paymentOptions = [
{ name: 'Option 1', value: 1 },
{ name: 'Option 2', value: 2 }
];
I want to filter array such data, when 'Option 1' is clicked, then all the elements with 'active':1 should be present in array. If user unselects 'option 1', then array should have all the elements. If 'Option 2' is clicked, then array should have only elements with 'active':0, If user unselects 'Option 2' then array should have all the elements. How can I do that?
You just need to pass your selection to component via ngModelChange and use it to run a filter on your array to get the desired result.
app.component.html (added some extra code to show the matching values):
<h5>Multiple Selection</h5>
<p-selectButton
[options]="paymentOptions"
[(ngModel)]="value2"
(ngModelChange)="filter($event)"
multiple="multiple"
optionLabel="name"
optionValue="value"
></p-selectButton>
<div>Selected option: {{value2}}</div>
<div *ngFor="let item of filteredItems">{{ item.name}}</div>
app.component.ts:
filter(data) {
if (data.length === 0) {
this.filteredItems = this.list;
return;
}
this.filteredItems = [];
this.filteredItems = this.list.filter(
(item) => data.findIndex((x) => (x === item.active && x !== 2) || (item.active === 0 && x === 2)) > -1
);
}