Eliminate any values that have not been chosen from the dropdown array in ngx-select-dropdown

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;
    }
  }

Visit this link for more details.

Answer №1

In the end, a simple solution presented itself - I had been overthinking the issue. All I needed to do was reset the this.filterState to ensure that the dropdown value only included selected options and not those that were deselected.

  adjustFilter(prop: string, newValue: any): void {
    this.filterState = {
      reds: [],
      blues: [],
      greens: []
    };

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angular binding for selecting all data

Upon checking a checkbox for a single item, the bound data is retrieved and added to an array. However, this does not happen when using selectAll. Code snippet in Angular for obtaining the object of a checked item: $scope.selectedOrganisations = []; $sco ...

Information displays instantly in the initial milliseconds

When developing dynamic web pages with Nuxt, I encountered an issue in the pages directory where a file named _url.vue is located. The contents of this file are as follows: <template lang="pug"> div component( v-for= ...

JavaScript event in Chrome extension triggers a browser notification and allows for modification using a specific method

I am currently developing a Chrome extension that is designed to take specific actions when system notifications appear, with the main goal being to close them automatically. One example of such a notification is the "Restore pages?" prompt: https://i.sta ...

Encountering SCRIPT1014 and SCRIPT1002 errors within an Angular4 application when using Internet Explorer 11

My Angular 4 application runs perfectly in various browsers. However, when trying to launch it in Internet Explorer version 11, I encounter the following two errors: SCRIPT1014: Invalid character addScript.js (9,1) SCRIPT1002: Syntax error main.bundle.js ...

Journeying through JSON: Presenting the value alongside its hierarchical parent

I'm completely new to JSON Path, so I'm not sure how complicated this could be, or if it's even possible. The JSON structure I have consists of multiple groups, each containing a set of fields. Both the groups and the fields have their own ...

Press the button to dynamically update the CSS using PHP and AJAX

I have been facing challenges with Ajax, so I decided to switch to using plain JavaScript instead. My goal is to create a button on a banner that will allow me to toggle between two pre-existing CSS files to change the style of the page. I already have a f ...

To enable the description p tag only when the search box text matches the search criteria, otherwise keep the p tag disabled

I need to develop a search feature that includes a search box, a heading, and a paragraph description. Initially, the description should be hidden, but when a user enters text that matches the description, the paragraph tag should become visible. An exampl ...

Tips for preventing multiple button clicks until the completion of the initial click event

I created a clock that tells the time every quarter as per the professor's request. However, there is an issue - when I click multiple times, the clock keeps telling the time repeatedly until the number of tellings matches the number of clicks. I thou ...

Issue encountered during installation of the robotjs npm package

Would appreciate any assistance with troubleshooting this issue. I've been grappling with it for 3 days, putting in countless hours of effort. The problem arises when attempting to install the robotjs npm package, as errors keep popping up. I've ...

Creating a CSS full-width navigation menu

Recently, I came across a menu code on the web that seemed great. However, I wanted to make my menu responsive and full width. Since I am new to CSS and HTML, adjusting the menu code has been a bit of a challenge for me. .menu, .menu ul { list-style: ...

Utilizing PHP to dynamically load HTML forms and leveraging JQuery for form submissions

I am currently facing a dilemma that I am unsure how to approach. It seems that JQuery requires unique ID's in order to be called in the document ready function. I use PHP to read my MySQL table and print out HTML forms, each with a button that adds a ...

Efficiently loading images asynchronously for smooth execution of JavaScript using Splide. Resolving Largest Contentful Paint (LCP) issue specifically on mobile

My webpage features a carousel of images at the top, created with Splide. However, I have noticed that my LCP score is significantly lower on mobile devices compared to desktop. The culprit seems to be in the Load Delay section: Time to first byte (TTFB) ...

AngularJS: Utilizing ellipsis for text overflow and optimization

As a beginner in angularJS, I might have made some mistakes... Can anyone guide me on how to properly implement this plugin: https://github.com/BeSite/jQuery.dotdotdot on my table? Currently, the performance of my edit form and table is very slow. What c ...

Is there a way to eliminate a specific input box using the jquery remove function?

I've been working on some code and have run into an issue. Currently, the remove function only works on one input box that is created with the append function. I would like it to be able to work on every input box generated through the append function ...

Communication between parents and children is crucial for building strong relationships and providing validation

This question may have been asked in a complex manner before, but I will simplify it here. In my main component, I have a form tag and Submit Button. Within this component, there is a child component that contains an input field with a required attribute, ...

Hunting for Two-Dimensional Patterns in a Grid

My original dataset consists of a 2D array with dimensions (640 x 480) and is derived from the pixel data captured by a camera. I am looking to identify specific patterns or objects within this image, focusing on objects of a certain size. Starting from ro ...

Transforming Jquery into vanilla JavaScript and sending a POST request

Hey everyone, I'm in the process of converting Jquery code to pure javascript and encountering some difficulties with the following snippet: $.post('ajax_data',{action:'service_price',service:service,quantity:quantity,dripfeed:drip ...

Artwork - Circular design disappears without warning

While working on a clock project purely for enjoyment, I noticed that the minute arc disappears from the canvas as soon as a new minute begins. Any idea why this is happening? Check out the clock in action: https://jsfiddle.net/y0bson6f/ HTML <canvas ...

Do constructors in TypeScript automatically replace the value of `this` with the object returned when using `super(...)`?

I’m having some trouble grasping a concept from the documentation: According to ES2015, constructors that return an object will automatically replace the value of “this” for any instances where “super(…)” is called. The constructor code must ...

Issue: Unable to find solutions for all parameters in (?, ?)

Below is the unit test I've written for my Angular 10 component, which showcases a tree view with interactive features: import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ReactiveFormsModule } from '@angular/for ...