Scenario: The challenge involves managing selected values in Angular applications using the ngx-select-dropdown. Users can select multiple values, which are then sorted into "buckets" and sent to the API.
Problem: I'm facing difficulty removing a selected item from the end array - this.filterState. Despite implementing a check to prevent duplicate entries (selecting and deselecting an item), manually removing the item with splice
when deselected seems ineffective as the dropdown only removes it from the value array without passing the deselected object's value.
const index = this.filterState[convertedParam].indexOf(value);
if (index === -1) {
this.filterState[convertedParam].push(value);
}
Suggested Solution: Perhaps adding a comparison mechanism upon event change to verify against the dropdown value object and previously submitted API array could resolve the issue.
Main Objective: Achieving the ability to add and remove objects from the sorted array.
Explore my solution on StackBlitz..
app.component.ts
handleFilterChange(prop: string, value: any): void {
// Consider adding comparison logic here between "value" and existing values in "this.filterState".
let field = this.fields.find(f => f.name === prop);
if (field.params) {
value.forEach(v => this.setFilterState(v.type, v, field));
} else {
this.setFilterState(prop, value, field);
}
console.log("SUBMITTED SORTED VALUES", this.filterState);
}
setFilterState(prop: string, value: any, field: Field): void {
const colourParamMap = {
I_am_RED: "reds",
I_am_BLUE: "blues",
I_am_GREEN: "greens"
};
if (field.name === "multiselect_1") {
const convertedParam = colourParamMap[prop];
const index = this.filterState[convertedParam].indexOf(value);
// Prevents duplicate entry and adds new value to the array
if (index === -1) {
this.filterState[convertedParam].push(value);
}
} else {
// Additional logic will be implemented here
this.filterState[prop] = value;
}
}