I have a add button which will keep on adding a div container which consists of two dropdowns. On selecting on dropdown we are setting other dropdown data.
When I click on add div it will add a second div with both dropdowns. But, change in one dropdown is affecting other dropdown.
app.component.ts
JavaScript
x
38
38
1
import { Component } from '@angular/core';
2
3
@Component({
4
selector: 'my-app',
5
templateUrl: './app.component.html',
6
styleUrls: ['./app.component.css'],
7
})
8
export class AppComponent {
9
private map = new Map<string, string[]>([
10
['Poland', ['Warszawa', 'Krakow']],
11
['USA', ['New York', 'Austin']],
12
]);
13
filtersList: any = [{}];
14
15
country: string;
16
city: string;
17
18
get countries(): string[] {
19
return Array.from(this.map.keys());
20
}
21
22
get cities(): string[] | undefined {
23
return this.map.get(this.country);
24
}
25
26
addFilter() {
27
this.filtersList.push({});
28
}
29
30
removeFilter(index) {
31
this.filtersList.splice(index, 1);
32
}
33
34
trackByIndex(index, item) {
35
return index;
36
}
37
}
38
app.component.html
JavaScript
1
14
14
1
<div *ngFor="let num of filtersList; let i = index; trackBy: trackByIndex">
2
<select [(ngModel)]="country">
3
<option *ngFor="let country of countries" [value]="country">
4
{{ country }}
5
</option>
6
</select>
7
8
<select *ngIf="country" [(ngModel)]="city" [value]="city">
9
<option *ngFor="let city of cities">{{ city }}</option>
10
</select>
11
<button (click)="removeFilter()">Remove</button>
12
</div>
13
<button (click)="addFilter()">Add more filters</button>
14
After adding div, each dropdown should have respective selected values.
Advertisement
Answer
So, when I click on add div it will add a second div with both dropdowns. But, change in one dropdown is affecting other dropdown.
That’s because these two dropdowns share the same variable/storage. You need to give them separate storage. In this case, we create a list of object with selectedCountry
and selectedCity
.
app.component.ts
JavaScript
1
24
24
1
// import stuff here
2
3
4
type Filter = {
5
selectedCountry: string;
6
selectedCity: string;
7
};
8
9
@Component({
10
11
})
12
export class AppComponent {
13
14
15
16
filterList: Filter[] = [];
17
18
addFilter() {
19
this.filterList.push({selectedCountry: '', selectedCity: ''});
20
}
21
22
}
23
24
app.component.html
JavaScript
1
18
18
1
<div *ngFor="let filter of filterList">
2
3
<select [(ngModel)]="filter.selectedCountry">
4
<option *ngFor="let country of countries" [value]="country">
5
{{ country }}
6
</option>
7
</select>
8
9
<select *ngIf="country" [(ngModel)]="filter.selectedCity" [value]="city">
10
<option *ngFor="let city of cities">{{ city }}</option>
11
</select>
12
13
<button (click)="removeFilter()">Remove</button>
14
15
</div>
16
17
<button (click)="addFilter()">Add more filters</button>
18