Eliminate a specific choice from a drop-down menu in an Angular application

I am implementing a feature where clicking on a button adds more select drop downs. I want to ensure that the selected options in these new dropdowns do not duplicate any already chosen options.

Below is the code snippet used for the select drop down:

<select class="select form-control"
   formControlName="environment_id" (change)="onEnvChange($event.target.value)">
   <option selected="selected" disabled value="">Select Environment
   </option>
   <ng-container  *ngFor="let environment of environments">
      <option *ngIf="!selectedEnvironments.includes(environment.environment_id)"
      [value]="environment.environment_id">
      {{environment.environment_id}}</option>
   </ng-container>
</select>

In the component, I have the following function for change:

 public onEnvChange(selectedEnvironment)
 {
     this.selectedEnvironments.push(selectedEnvironment);
 }

The issue is that when an option is selected, it gets removed from the dropdown altogether. How can I modify the code so that the selected option is only removed from the next select dropdown?

Answer №1

You may consider creating two instances of environments and monitoring selection changes using valueChanges from formControl. Once you have the selected environmentid, filter the other object to exclude this id.

For example:

  ngOnInit(){
    this.initializeForm();
    this.retrieveEnvironments();
    this.trackEnvironmentChanges()
  }

  initializeForm(){
      this.form = this.fb.group({
           'environment_id_1': [''],
           'environment_id_2' : ['']
})}

  retrieveEnvironments(){
      const environments = [
      {  'environment_id': 1, 'environment': 'A'  },
      {  'environment_id': 2, 'environment': 'B'  },
      {  'environment_id': 3, 'environment': 'C'  },
      {  'environment_id': 4, 'environment': 'D'  }];
      this.environments1 = environments;
      this.environments2 = environments;}

  trackEnvironmentChanges(){
     this.form.controls['environment_id_1'].valueChanges
             .subscribe((environment_id)=>{
             this.environments2 = this.environments1.filter((env)=> env.environment_id != environment_id)
})}

<form [formGroup]="form">
<div class="row">
    <select class="select form-control"   formControlName="environment_id_1">   
        <option value="">Select Environment 1 </option> 
        <option *ngFor="let environment of environments1"  [value]="environment.environment_id"> {{environment.environment}} </option> 
    </select>
</div>
<div class="row" style="padding-top: 10px;">
    <select class="select form-control"   formControlName="environment_id_2">   
        <option value="">Select Environment 2 </option> 
        <option *ngFor="let environment of environments2"  [value]="environment.environment_id"> {{environment.environment}} </option> 
    </select>
</div>

image description here

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

Despite being installed, the message 'concurrently: command not found' pops up

I'm attempting to run two scripts simultaneously, and I came across the concurrently package that is supposed to assist with this. After executing npm install concurrently --save and verifying it in my package.json, I faced an issue when trying to run ...

Arrange, Explore (Refine), Segment HTML Chart

Is there a way to efficiently sort, paginate, and search (based on a specific column) data in an HTML table? I've explored several JQuery plugins such as DataTable, TableSorter, Picnet Table Filter, but none seem to offer all three functionalities (se ...

Aggregate values through an onclick event using a get request and iterate through each using

I am struggling to accumulate values obtained from a json get request using jQuery. The problem is that the values keep getting replaced instead of being added up in the variable total. Can someone please guide me on how to properly sum up the values with ...

Tips for Retrieving a JavaScript Variable's Value in JSP

In my JSP file, I have implemented dynamic rows of textboxes using JavaScript. Now that I have input values into these fields, how can I retrieve those values in my result JSP page? ...

Utilize Javascript and JQuery to implement sending a custom header in an OPTIONS preflight API request

Snippet: $.ajax({ type: 'GET', dataType: 'json', url: api, xhrFields: { withCredentials: true }, beforeSend: function (xhr) { xhr.setRequestHeader('Authorization', "Basic [my auth token]"); }, ...

Zero Clipboard may experience functionality issues if it is invoked dynamically

Copying to the clipboard is made possible with Zero Clipboard, a tool recommended in this answer. The code functions perfectly when used as shown below: <div id="d_clip_button" style="background: #FFFFCC;"> Click to copy </div> <script ...

Making a Cross-Origin Resource Sharing (CORS) request with jQuery utilizing the $

I am currently in the process of building a web application that relies heavily on data from multiple domains. Approximately 90% of the requests made by my application are cross-domain requests. However, I have encountered an issue where I am unable to re ...

Accessing the form element in the HTML outside of the form tag in Angular 2

I am attempting to achieve the following: <span *ngIf="heroForm?.dirty"> FOO </span> <form *ngIf="active" (ngSubmit)="onSubmit()" #heroForm="ngForm"> <div class="form-group"> <label for="name">Name</label& ...

Backdrop dimming the Material UI Modal

My modal is designed to display the status of a transaction on my website, but I'm facing an issue where the backdrop dimming effect is being applied over the modal. Instead of appearing white as intended, the modal ends up having a dark gray tint. I ...

Tips for getting a plugin to function properly when the page is refreshed in Nuxt app

I am currently incorporating the vue GAPI plugin into my project. While it functions smoothly when navigating between pages, I encounter an error upon refreshing: vue-gapi.common.js?15fd:241 Uncaught (in promise) Error: gapi not initialized at GoogleAuth ...

The loading time for the Docker index HTML file page is unacceptably slow

Sample Dockerfile: FROM ubuntu:22.04 RUN apt-get update RUN apt-get install -y nginx COPY -r dist/ /var/www/html/ CMD service nginx start && tail -F /var/log/nginx/error.log After that, run the following commands: docker build -t website . docker ...

Creating redux reducers that rely on the state of other reducers

Working on a dynamic React/Redux application where users can add and interact with "widgets" in a 2D space, allowing for multiple selections at once. The current state tree outline is as follows... { widgets: { widget_1: { x: 100, y: 200 }, widg ...

Ensure that the default value in the text box remains unchanged until new text is input by utilizing jQuery

Can you please review my code snippet on http://jsfiddle.net/7995m/? The issue I'm facing is that the default text in the text box disappears as soon as it's clicked. What I want is for the default text to remain until the user starts typing. Her ...

Retrieving components of an array

I am looking to extract elements from an array, then store them in a new array and compare them to another array. The challenge is that I do not want to extract the elements in a specific order. I have tried using the .slice function for extracting element ...

What seems to be the issue with loading this particular file into my JavaScript code?

When attempting to import a file into my code, I encountered an issue where the folder could not be found. Interestingly, when manually typing out the folder name, it is recognized and suggested by the system. Even providing the full path did not yield dif ...

Tips for loading images dynamically (or lazily) as they come into the user's view with scrolling

Many modern websites, such as Facebook and Google Image Search, display images below the fold only when a user scrolls down the page enough to bring them into view (even though the page source code shows X number of <img> tags, they are not initially ...

Switching up the default font style within TinyMCE

After successfully changing the default font within the editor using the guidelines provided here, I have encountered a new issue. The original default font no longer appears in the font drop-down list. The previous default font was Verdana, and the new d ...

.submit fails to function when the bound object has been updated via an ajax call

I managed to implement an AJAX commenting system where, upon clicking the Post Comment button, an ajax call is made instead of submitting the form traditionally. Everything was working smoothly until I tried refreshing the page with the comment submit butt ...

Receiving Server Emissions in Vue/Vuex with Websockets

In my Vue component, I was using socket.io-client for WebSocket communication. Now that I've added Vuex to the project, I declared a Websocket like this: Vue.use(new VueSocketIO({ debug: true, connection: 'http://192.168.0.38:5000', })) ...

Automatically updating quantity with the power of jQuery

I have created a spreadsheet where users can input their expenses and the total will update automatically. Initially, I have set some default numbers in my HTML which are editable for users to modify as needed. However, I am facing an issue with my JQuer ...