context: Angular applications using the ngx-select-dropdown. A user can select multiple values, these values get sorted into "buckets" and sent to the api.
Issue: I am unable to remove a selected item from the end array - this.filterState. I have added a check to ensure that an item cant be added more than once - a click to select the item and a click to deselect the item. I thought that this would be a good time to remove the item with a splice
as the user would have clicked to deselect if it already exists in the array - however, the dropdown does not pass the value of a deselected object it just removes it from the value array of the dropdown.
const index = this.filterState[convertedParam].indexOf(value);
if (index === -1) {
this.filterState[convertedParam].push(value);
}
Proposed solution: I think it will need some sort of comparison upon event change against the dropdown value object and the array that was previously sent to the api.
End goal: To be able to add and remove objects from the sorted array
Here is a stackblitz that I put together...
app.component.ts
handleFilterChange(prop: string, value: any): void {
// I think the comparison with "value" and whats already in "this.filterState" will need to be done here?
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);
//stops from adding same value again and adds value to array
if (index === -1) {
this.filterState[convertedParam].push(value);
}
} else {
//There will be more logic here
this.filterState[prop] = value;
}
}
https://stackblitz.com/edit/ngx-select-dropdown-xkfbyr?file=app%2Fapp.component.ts
A simple fix in the end - I was trying to over complicate things. I needed to reset the this.filterState
as the value from the dropdown will include every value from before, minus the ones that were deselected.
handleFilterChange(prop: string, value: any): void {
this.filterState = {
reds: [],
blues: [],
greens: []
};