I tested to make states
and city
cascading dynamic dropdownlists, i created two dropdownlist
, state
and city
, i want to populate drowdownlist
with corresponding cities
to state
but it doesn't work, it just works for the 1st time.
I don't know how to fix this problem
select.component.ts
ngOnInit(): void {
}
states:any=[
{id: 1,name: "Maharasthra"},
{id: 2,name: "West Bengal"}
];
cities:any=[
{id: 1,name: "Mumbai",state_id:1},
{id: 1,name: "Pune",state_id:1},
{id: 2,name: "Kolkata",state_id:2},
{id: 2,name: "Howrah",state_id:2}
];
onSelect(state:any){
this.cities = this.cities.filter((item:any) => item.state_id == state.target.value);
console.log(state.target.value)
}
select.component.html
<div >
<div >
<label>states <span >*</span></label>
<select (change)="onSelect($event)">
<option [value]="0">--select--</option>
<option [value]="i.id" *ngFor="let i of states" >{{ i.name }}</option>
</select>
</div>
<div >
<label>city <span >*</span></label>
<select >
<option [value]="c.id" *ngFor="let c of cities">{{ c.name }}</option>
</select>
</div>
</div>
CodePudding user response:
the problem is that you're overwriting your cities array. you can try something like:
ngOnInit(): void {
}
states:any=[
{id: 1,name: "Maharasthra"},
{id: 2,name: "West Bengal"}
];
allCities = [
{id: 1,name: "Mumbai",state_id:1},
{id: 1,name: "Pune",state_id:1},
{id: 2,name: "Kolkata",state_id:2},
{id: 2,name: "Howrah",state_id:2}
];
cities = []
onSelect(state:any){
this.cities = this.allCities.filter((item:any) => item.state_id == state.target.value);
console.log(state.target.value)
}