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

Executing a POST Request from AngularJS to a server-side script

Currently, I am in the process of developing a web application using Yeoman tools with AngularJS. However, I have encountered a challenge when trying to send a POST request to a server-side script from a controller. Below is the snippet of code from my con ...

Error in NextJS: The name 'NextApplicationPage' cannot be found

const { Component, pageProps}: { Component: NextApplicationPage; pageProps: any } = props After implementing the code above with 'Component' type set to NextApplicationPage, an error message pops up stating, The name 'NextApplicationPage&ap ...

Color picker can be utilized as an HTML input element by following these steps

After trying out various color pickers, I was not satisfied with their performance until I stumbled upon Spectrum - The No Hassle jQuery Colorpicker. It perfectly met my requirements. <html> <head> <meta http-equiv="content-type" content="t ...

jQuery UI dynamically adjusting content layout based on browser size changes

Having an issue with my custom accordion script where resizing the browser causes formatting problems in one of the sections. I want the content to remain intact and to utilize a scrollbar if necessary to view the content. The problem is visible in section ...

Can you provide some guidance on utilizing a for loop within Angular?

Storing the values entered by the user in an input field as "values" and having another array, "existing userdetails," returned from the backend that contains all details of existing users, I am faced with the task of comparing these two sets of data. I h ...

What is the most efficient way to perform an array join in Node.js, akin to the speed of MongoDB's $

Looking to implement a $lookup function in Node.js similar to the $lookup aggregation in MongoDB. I have a solution in mind, but I'm unsure about its performance when dealing with larger arrays or bigger objects. let users = [ {userId: 1, name: ...

Save the entire compiler output as a text or CSV file by using the "strict":true compiler option in TypeScript

The tsconfig.json file in my Visual Studio project includes the following settings: { "CompileOnSave":false, "CompilerOptions":{ "strict": true, "skipLibCheck":true }, "angularCompilerOptions":{ "fullT ...

What could be causing the NoScript tag to malfunction across different web browsers?

I've incorporated the NoScript tag into my JSP pages in the head section. To avoid conflicts with tiles, I made sure not to include multiple NoScript tags. However, I am experiencing issues in Internet Explorer where it doesn't seem to be working ...

The bond between TypeORM and express

I am working on establishing Many-to-One and One-to-Many relationships using TypeORM and MySQL with Express. The database consists of two tables: post and user. Each user can have multiple posts, while each post belongs to only one user. I want to utilize ...

Unable to pass parameters through the URL in Angular's POST request

Hey there! I'm currently facing an issue with passing a parameter in the POST method URL within an Angular service to construct a URL for fetching data from an API. However, when I try calling it in the component file, I keep getting an error response ...

Here is an example of how to use a script tag to check the value of a select tag in HTML:

Hi there! I'm working on a piece of code where I need to retrieve the selected value from a dropdown menu in an HTML select tag and display it in the element with the id='h1' at the bottom. The script tag is already included within the head ...

Trouble with innerHTML in a for loop when using getJSON

My current challenge involves displaying a series of JSON results within a div tag using innerHTML. <script> $(document).ready(function() { var html2 = ''; var thread_id = ''; var created_thread_ids ...

"Have you ever wondered how the router object in express.js is seamlessly integrated with app.use(), considering that it only accepts

I am curious about the process of how the router object in express.js is passed to app.use(), which typically only accepts callbacks. Since router is an object of express, I am trying to understand why app.use() does not throw an error even though it req ...

Unusual shadow cast by the box's silhouette

I am currently facing an issue with a box and its shadow. When I close the box, a different shadow lingers behind. I have tried troubleshooting this problem but cannot pinpoint the source. I have included the relevant code files in the specified folders. I ...

Methods for ensuring that fake browser tab focus remains on several tabs simultaneously

Is there a way to simulate multiple tab/window focus in a browser for testing purposes? I need to test pages that require user input and focus on active windows/tabs. Are there any different browsers, plugins, or JavaScript code that can help me achieve th ...

Tips for resolving the problem when encountering the "undefined data" issue in the success callback of an AJAX request

I am facing an issue with my JSP page where I have a button that calls an Ajax method named "sendmail()" upon click. The send mail API is in the Controller, and I am trying to display an alert message in the Ajax success function using data.message, but it ...

worldpay implements the useTemplateForm callback function

My experience with implementing worldpay on my one-page Angular app (Angular 1.x) has been mostly positive. I have been using the useTemplateForm() method to generate a credit card form and retrieve a token successfully. However, I have encountered an issu ...

Display the checkbox as selected using AngularJS

I have already submitted a form with a checkbox value. Now, I am trying to display the checkbox as "checked" using AngularJS based on the value retrieved from the data source. Can someone guide me on how to achieve this? ...

The Conundrum of Angular 5 Circular Dependencies

I've been working on a project that involves circular dependencies between its models. After reading through this StackOverflow post and its suggested solutions, I realized that my scenario might not fit into the category of mixed concerns often assoc ...

Encountering error code 128 while attempting to download npm packages

After attempting to install jspdf using the command npm install jspdf --save, I encountered the following error: npm ERR! code 128 npm ERR! Command failed: git submodule update -q --init --recursive npm ERR! error: waitpid for git-submodule failed: No chi ...