问题描述
我收到了来自三个 diff API 的 angular 响应。 由于我们相互依赖,因此所有 API 都在 ngOnInit 中调用。 如何制作级联下拉菜单,就像我从第一个下拉菜单中选择了“印度”,那么印度的所有城市都应该出现在第二个下拉列表中,当我从第二个下拉列表中选择德里时,德里的所有值都应该出现在第三个下拉列表中
API 1 响应
{id: 0,name: "India"}
{id: 1,name: "US"}
API 2 响应
{id: 0,name: "India",city: "delhi"}
{id: 1,name: "US",city: "NYK"}
{id: 2,city: "chennai"}
{id: 3,city: "WDC"}
{id: 4,city: "mumbai"}
{id: 5,city: "NewJs"}
API 3 响应
{id: 0,name: "block1",dist: "delhi"}
{id: 1,name: "block2",dist: "NYK"}
{id: 2,name: "block3",dist: "Chennai"}
{id: 3,name: "block4",dist: "delhi"}
{id: 4,name: "block5",dist: "WDC"}
{id: 5,name: "block6",dist: "NewJs"}
{id: 6,name: "block7",dist: "mumbai"}
{id: 7,name: "block8",dist: "delhi"}
{id: 8,name: "block9",dist: "NYK"}
component.ts
export class CreateInfraRequestComponent implements OnInit {
Country:any;
City:any;
Block:any;
selectedCountry:any;
selectedCity:any;
selectedBlock:any;
constructor(private infraService : InfraRequestService){ };
ngOnInit(): void {
this.getAllCountry();
this.getAllCity();
this.getAllblock();
}
getAllCountry (){
this.infraService.getAllInfraRequest("apiUrlForCountyr").subscribe((data)=>{
this.Country=data;
console.log(data);
});
}
getAllCity(){
this.infraService.getAllInfraRequest("apiUrlForCity").subscribe((data)=>{
this.City=data;
console.log(data);
});
}
getAllblock(){
this.infraService.getAllInfraRequest("apiUrlForBlock").subscribe((data)=>{
this.Block=data;
console.log(data);
});
}
}
component.html
<select [(ngModel)]="selectedCountry">
<option *ngFor="let country of Country" [value]="country.name">
{{country.name}}
</option>
</select>
<select [(ngModel)]="selectedCity">
<option *ngFor="let city of City" [value]="city.name">
{{city.name}}
</option>
</select>
<select [(ngModel)]="selectedBlock">
<option *ngFor="let block of Block" [value]="block.name">
{{block.name}}
</option>
</select>
解决方法
解决问题的一种方法是使用 change 事件监听更改。你想做的是
-
每次发生选择更改时触发更改事件:
{国家的名字}} -
然后在 ts 文件中使用 - 访问值并将其分配给下一个选择项
onChange(newValue) { console.log(newValue); this.City = newValue; }
这篇文章可以帮助您进一步: How can I get new selection in "select" in Angular 2?