The alterations made to a single dropdown option are causing ripple effects across all other dropdowns

There is an add button that continuously adds a div container containing two dropdowns. The selection in one dropdown affects the data in the other dropdown.

When the add button is clicked, a second div with both dropdowns is added. However, changing the value in one dropdown affects the other dropdown.

app.component.ts

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

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  private map = new Map<string, string[]>([
    ['Poland', ['Warszawa', 'Krakow']],
    ['USA', ['New York', 'Austin']],
  ]);
  filtersList: any = [{}];

  country: string;
  city: string;

  get countries(): string[] {
    return Array.from(this.map.keys());
  }

  get cities(): string[] | undefined {
    return this.map.get(this.country);
  }

  addFilter() {
    this.filtersList.push({});
  }

  removeFilter(index) {
    this.filtersList.splice(index, 1);
  }

  trackByIndex(index, item) {
    return index;
  }
}

app.component.html

<div *ngFor="let num of filtersList; let i = index; trackBy: trackByIndex">
  <select [(ngModel)]="country">
    <option *ngFor="let country of countries" [value]="country">
      {{ country }}
    </option>
  </select>

  <select *ngIf="country" [(ngModel)]="city" [value]="city">
    <option *ngFor="let city of cities">{{ city }}</option>
  </select>
  <button (click)="removeFilter()">Remove</button>
</div>
<button (click)="addFilter()">Add more filters</button>

Once a div is added, each dropdown should retain its selected values independently.

Answer №1

Whenever I click on the add div button, it adds a second div containing both dropdowns. However, changing an option in one dropdown affects the other dropdown as well.

This is happening because both dropdowns are using the same storage variable. To fix this issue, you need to provide separate storage for each dropdown. One way to achieve this is by creating a list of objects with properties like selectedCountry and selectedCity.

app.component.ts


// import necessary modules


type Filter = {
  selectedCountry: string;
  selectedCity: string;
};

@Component({
...
})
export class AppComponent {

  ...
  
  filterList: Filter[] = [];

  addFilter() {
    this.filterList.push({selectedCountry: '', selectedCity: ''});
  }

}

app.component.html

<div *ngFor="let filter of filterList">

  <select [(ngModel)]="filter.selectedCountry">
    <option *ngFor="let country of countries" [value]="country">
      {{ country }}
    </option>
  </select>

  <select *ngIf="country" [(ngModel)]="filter.selectedCity" [value]="city">
    <option *ngFor="let city of cities">{{ city }}</option>
  </select>

  <button (click)="removeFilter()">Remove</button>

</div>

<button (click)="addFilter()">Add more filters</button>

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

Tips for maintaining a persistent login session in React Native with Firebase forever

I've been grappling with this issue for a few days now. Essentially, my aim is to have Firebase remember the user so they remain logged in after logging in once. The first block of code is the App component (I've omitted some of the irrelevant co ...

Vue.js Interval Functionality Malfunctioning

I'm brand new to Vuejs and I'm attempting to set an interval for a function, but unfortunately it's not working as expected. Instead, I am encountering the following error: Uncaught TypeError: Cannot read property 'unshift' of u ...

The element ion-view is not recognized

Here is the content I have for my Ionic page: <ion-content padding class = ""view-content"> <form> [form content here...] </form> </ion-content> This is the CSS code from my file: .view-content { backg ...

Leveraging the power of jQuery Validation in conjunction with Bootbox

I am currently facing an issue with integrating the jQuery validation plugin with bootbox.js (modals). The modal contains a form with fields that require validation. To showcase my problem, I have set up a jsFiddle here: http://jsfiddle.net/rDE2q/ Upon ...

The Ajax page does not respond to click events when the function is declared within $(function(){ }) block

Create two functions as shown below: <script> $(function () { function myFunctionB() { alert("ddd"); } }) function myFunctionA() { alert("ddd"); } </sc ...

myObject loop not functioning properly in Internet Explorer version 10

Could someone please point out what is wrong with this code snippet? HTML: <div id="res"></div> Javascript: var myObject = { "a" : { src : "someimagepath_a.png" }, "b" : { src : "someimagepath_b.png" }, }; va ...

Tips for transmitting HTML as a JSON object through the res.render function in expressjs

My issue involves a JavaScript function that returns an HTML element. I want to pass this element along for users to view as actual HTML, but it ends up appearing as a string with special characters like "<" and ">". For example, "<" appears as (& ...

Looking to include some extra padding when an item is displayed - jQuery

So, I'm working on a jQuery code snippet that controls the visibility of a rectangle element: $("#rectangle").hide(); $("#toggle-rec").click(function () { $("#rectangle").toggle(2000); }); This code hides the rectangle initially and toggles it ...

Is there an Angular directive that can replicate a mouseenter event?

Is there a way to simulate a mouseenter event with a directive? I have been searching for a directive that can simulate a mouseenter event, but all I have found so far is one that binds a function to mouse over or karma tests for simulating mouse over. W ...

Choosing specific elements with Selenium using OR/AND operations in Python

I am encountering an issue while working with Selenium using Python. Here is a preliminary example of my code snippet. <body> <button info="content1" aria-label="1">"Click 1"</button> <button info ...

Is the Three.JS camera update causing issues with the shader?

Attempting to replicate the Bubble shader from https://github.com/stemkoski/stemkoski.github.com/blob/master/Three.js/Bubble.html, but encountering issues due to outdated code. The example should refract whatever is behind it, like this: https://i.sstatic ...

What is the best way to define an event binding statement in the Angular code rather than within the template?

Is it possible to define the event binding statement directly in the code (rather than in the template)? I am trying to dynamically create a menu, and while I can achieve this with routes (since they are strings), using event names seems to be more challe ...

Trouble with incrementing JavaScript dictionary values within a nested for loop

I am currently working on analyzing shark attack data with d3.js using a csv file named shark.csv. I have encountered a problem while implementing a nested for-loop in my code. The csv file contains information about shark attacks categorized by continent ...

Using TypeScript to incorporate JS web assembly into your project

I have been attempting to incorporate wasm-clingo into my TypeScript React project. I tried creating my own .d.ts file for the project: // wasm-clingo.d.ts declare module 'wasm-clingo' { export const Module: any; } and importing it like this: ...

Continuously flowing chain of replies from a series of queries using RxJS

I am exploring the world of RxJS and seeking guidance from experienced individuals. My goal is to establish a synchronized flow of responses, along with their corresponding requests, from a stream of payload data. The desired approach involves sending ea ...

Save the ID of the list item by wrapping it and storing it in a table cell

I need help with a situation where I have a list of items stored in table cells, and each cell contains a list item. My goal is to save the id of each list item into the cell that contains it. For example: <td><li id='itemID'>content ...

After clicking, the React mobile navigation fails to collapse

At a certain breakpoint, my mobile navigation bar appears with a MENU button. When the MENU button is clicked, the menu opens and the button changes to CLOSE. Clicking on CLOSE collapses the menu, returning the button to MENU. However, when I click on th ...

I'm looking to keep the footer anchored at the bottom without using the absolute positioning

I am currently developing a website and have implemented a wrapper for the footer. My goal is to create a sticky footer, but when I minimize the screen, the footer ends up overlapping with the content and header. #footerWrapper { height: 177px; bottom: ...

Issue encountered when attempting to run "ng test" in Angular (TypeScript) | Karma/Jasmine reports an AssertionError stating that Compilation cannot be undefined

My development setup includes Angular with TypeScript. Angular version: 15.1.0 Node version: 19.7.0 npm version: 9.5.1 However, I encountered an issue while running ng test: The error message displayed was as follows: ⠙ Generating browser application ...

Customizing the initial page layout in Elm

I am new to Elm and I need help with a particular issue. Can someone provide guidance or direct me to a useful resource for solving this problem? The challenge I’m facing involves editing the start page of a website by removing specific elements, as list ...