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.