Delete an item from an array when a dropdown selection is made

When dealing with Angular 8, I encountered a logic issue.

There are two drop-down menus:

First Drop-down

  • The options in the first menu are populated from an array of objects

    Example Code, ts:

       {rs_id: "a5f100d5-bc88-4456-b507-1161575f8819",
        rs_code: "100006",
        rs_name: "Leanbox Logistics Solutions Pvt Ltd"} , 
     {rs_id: "a5f100d5-bc88-4456-b507-116157523345",
     rs_code: "123406",
     rs_name: "xysa Solutions Pvt Ltd"} , 

     {rs_id: "a5f100456-b507-116157523345",
     rs_code: "123406223",
     rs_name: "Solutions Pvt Ltd"} , 
  ]

html

<option>
    <select  (change)="getRsId($event)"  > 
    <option [value]='data.rs_id' *ngFor='let data of s_rsList  ; let i = index'> {{data.rs_name}} </option>



</select>
  • The options in the second drop-down menu are obtained from the same array of objects, but the object selected in the first drop-down should be removed from the Array.

Full code example:

slackbliz link ->

https://stackblitz.com/edit/angular-7lgyfe?file=src%2Fapp%2Fapp.component.html

html

<div> 

<p> First DropDown </p>

<select  (change)="getRsId($event)"  > 
<option [value]='data.rs_id' *ngFor='let data of s_rsList  ; let i = index'> {{data.rs_name}} </option>
</select>


<p> Second DropDown </p>

<select  (change)="getRsId($event)" > 
<option [value]='data.rs_id' *ngFor='let data of r_rsList  ; let i = index'> {{data.rs_name}} </option>
</select>



</div>

ts

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';

  s_rsList  :any = [
    {rs_id: "a5f100d5-bc88-4456-b507-1161575f8819",
     rs_code: "100006",
     rs_name: "Leanbox Logistics Solutions Pvt Ltd"} , 


     {rs_id: "a5f100d5-bc88-4456-b507-116157523345",
     rs_code: "123406",
     rs_name: "xysa Solutions Pvt Ltd"} , 

     {rs_id: "a5f100456-b507-116157523345",
     rs_code: "123406223",
     rs_name: "Solutions Pvt Ltd"} , 
  ]

  r_rsList : any = [] 


  constructor(){}


  getRsId(value){



    console.log(value);


    let Rsindex =   value.target['selectedIndex'];
    console.log(Rsindex);
    this.r_rsList.splice(Rsindex, 1);


  }
}

Answer №1

To filter the second array based on ngModel values of select elements, you can utilize a get property.

  selected_R_Item;
  selected_S_Item;

  get r_rsList() {
    return this.s_rsList.filter(item => item.rs_id !== this.selected_S_Item )
  }  

Htm;

<select [(ngModel)]="selected_S_Item"     > 
<option [value]='data.rs_id' *ngFor='let data of s_rsList  ; let i = index'> {{data.rs_name}} </option>
</select> 

<select  [(ngModel)]="selected_R_Item"   > 
<option [value]='data.rs_id' *ngFor='let data of r_rsList  ; let i = index'> {{data.rs_name}} </option>
</select>

Demo

Answer №3

To efficiently manage your data, consider using two separate arrays:

In your TypeScript file:

s_mainArray = [.....] // Your main array
s_secondaryArray;

constructor() {
  this.s_secondaryArray = this.s_mainArray;
}

getFilteredData(value){
    let index = value.target['selectedIndex'];
    console.log(index);
    this.s_secondaryArray = this.s_mainArray.filter((value, idx) => idx != index)
}

In your HTML:

<select (change)="getFilteredData($event)"> 
  <option [value]='item.id' *ngFor='let item of s_mainArray; let i = index'> 
    {{item.name}} </option>
</select>




<select (change)="getFilteredData($event)"> 
  <option [value]='item.id' *ngFor='let item of s_secondaryArray; let i = index'> 
    {{item.name}} </option>
</select>

Answer №4

I have updated your TypeScript file based on the requirements you provided.

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';

  s_rsList  :any = [
    {rs_id: "a5f100d5-bc88-4456-b507-1161575f8819",
     rs_code: "100006",
     rs_name: "Leanbox Logistics Solutions Pvt Ltd"} , 


     {rs_id: "a5f100d5-bc88-4456-b507-116157523345",
     rs_code: "123406",
     rs_name: "xysa Solutions Pvt Ltd"} , 
  ]

  r_rsList : any = [] 

  constructor(){}


  getRsId(value){



    console.log(value);
    let Rsindex =   value.target['selectedIndex'];
    console.log(Rsindex);
    this.r_rsList=this.s_rsList.slice();
    this.r_rsList.splice(Rsindex,1)
  }
}

Answer №5

Erase the (change)="fetchRsId($event)" from the second dropdown menu, update fetchRsId to:

 fetchRsId(selection) {
   this.filtered_rsList = this.available_rsList.slice();
   this.filtered_rsList.splice(selection.target["selectedIndex"], 1);
 }

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

How can we stop the jumping of images in the grid? Is there a way to eliminate the jump effect?

Here is a script I am working with: <script src="http://static.tumblr.com/mviqmwg/XyYn59y3a/jquery.photoset-grid.min.js"></script> <script> $(document).ready(function() { $('.photoset-grid').photose ...

The issue of AngularJS failing to bind object properties to the template or HTML element

Just dipping my toes into angularJS, following Todd Motto's tutorials, and I'm having trouble displaying object properties on the page. function AddCurrentJobs($scope){ $scope.jobinfo = [{ title: 'Building Shed', description: ...

"Troubleshooting: Issue with updating page CSS in browser when using npm, node-sass, and concurrent in an

Embarking on a new Angular2 project to enhance my skills, I've made the decision to avoid Yeoman Generator and tools like Grunt or Gulp due to the software still being in development. Instead, I'm utilizing the Node Package Manager to run automat ...

The onchange function seems to be malfunctioning when attempted with AJAX

Help needed: I'm new to AJAX and facing an issue. I have implemented AJAX pagination to display data, which is working fine. But now I want to add a filter to the displayed data, however, the filter is not functioning correctly. <select name="prof ...

A node module designed to efficiently convert multiple TIFF images into a single multipage TIFF document

Looking to combine several tiff images into a single file using nodejs/javascript. Is there a method to create a single tiff file with multiple pages from separate tiff images in nodejs? Can we convert a multi-page pdf into one tiff image using nodejs? ...

Utilizing FullCalendar for showcasing comprehensive details

I'm a big fan of the fullcalendar plugin and all its amazing features. I want to enhance it by displaying more customized information for each event when in agendaWeek or agendaMonth view. Switching between views is easy, but I need help filtering out ...

Unexplainable space or padding issue detected in OwlCarousel grid gallery

There seems to be an unusual gap or margin at the bottom of each row section in this portfolio grid gallery that's running in OwlCarousel. You can view an example here. https://i.stack.imgur.com/NHOBd.png I've spent a lot of time trying to solv ...

When creating a responsive datatable in Angular, be aware that the reference to "this.table

Here is the code from my datatable.component.ts: import { Component,AfterViewInit, OnDestroy,ElementRef, ViewChild, OnInit } from '@angular/core'; declare var $; import { Http, Response } from '@angular/http'; import { Subj ...

Is it possible to update the state of an array within a .then() function in React?

` After retrieving an array of points with city and state information, I attempted to convert these points to latitude and longitude by making a fetch call. However, upon trying to update the state of the newly generated array, I found that it remained ...

extract element from a string with the help of jquery

When using AJAX to request HTML from a page, the process involves sending a request like this: function getHTML() { //set ajax call var options = { url: '/Controller', type: 'GET', d ...

What is a way to nest a promise request within another request?

Q: How can I create a new promise within a request, and then return it in a nested request? Here is the code snippet: request({ // --------------request 1------------ url: request_data.url, method: request_data.method, form: request_data.data ...

The Selenium driver's execute_script() function is not functioning as expected

When I attempt to execute a JavaScript using driver.execute_script, nothing happens and the system just moves on to the next line of Python code. Any ideas? I've been web scraping on a webpage, using JavaScript in the Console to extract data. The Jav ...

Typescript's dynamic React component and its conditional types

I am currently working on a dynamic React component and I am facing an issue with properly passing the correct propType based on the selected component. The error arises when using <SelectComponent {...props.props} /> because the props do not match t ...

Leveraging the outcome of an API request with Protractor

I have developed a small API that generates test data instantly. Each request creates a new user and provides the relevant data. For fetching the data, I utilize the 'request' package: var flow = protractor.promise.controlFlow(); var result = f ...

Encountered an issue locating the stylesheet file 'css/style.css' that is supposed to be linked from the template. This error occurred when trying to integrate Bootstrap with Angular

<link rel="stylesheet" href="plugins/bootstrap/bootstrap.min.css"> <link rel="stylesheet" href="plugins/owl-carousel/owl.carousel.css"> <link rel="stylesheet" href="plugins/magnific-pop ...

What is the process of synchronizing state in react.js?

I am struggling to update the state and component in my code. When I press a button and change the value of one of the props in the popup component, the prop value does not get updated. I suspect this issue is due to using setState. I researched a possible ...

javascript guide to dynamically update the glyphicon based on value changes

I am attempting to implement an optimal level feature where a glyphicon arrow-up will be displayed if a value falls within the optimum range, and it will switch to a glyphicon arrow-down if the value is lower. <div class="card-body" ng-repeat="item i ...

Invoking a class method in Javascriptcore on iOS

I'm currently trying to comprehend the inner workings of JavascriptCore. Initially, I attempted calling a single function. Now, my focus has shifted to invoking a function within a class. This is what my javascript code looks like: var sayHelloAlf ...

Developing an ASP application using the MVP pattern to return JSON data can be transformed into a S

I’m looking to incorporate the following code into a sails js Controller public JsonResult GetEvents() { //Using MyDatabaseEntities as our entity datacontext (refer to Step 4) using (MyDatabaseEntities dc = new MyDatabaseEntities()) { ...

Loader for dynamically loading tabs in Angular 2

I am looking to develop a dynamic tabs loader using Angular 2 material with specific syntax support. <generic-tabs [tabs]="tabs" tabVisibleField="name"> <test-cmp [tabContent] testData="hello"></test-cmp> ...