我正在处理Angular 4反应形式。这里我有一个带有一些输入字段的表格。基于一个字段数据,即将到来的字段数据将被更改。我需要根据以前的下拉列表显示国家/地区和所有城市使用angular 4进行选择。我尝试了很多,但没有找到有效的解决方案。有人可以帮我使用此json对此进行排序。
{
"Countries":[
{
"id":0,
"CountryName":"Indonesia",
"States":[
{
"id":0,
"StateName":"Bali",
"Cities":[
{
"id":0,
"CityName":"Denpasar",
"Municipalities":[
{"id":0,"MunName":"Mun1"},
{"id":1,"MunName":"Mun2"},
{"id":2,"MunName":"Mun3"}
]
},
{
"id":1,
"CityName":"Kuta",
"Municipalities":[
{"id":0,"MunName":"Mun4"},
{"id":1,"MunName":"Mun5"},
{"id":2,"MunName":"Mun6"}
]
},
{
"id":2,
"CityName":"Tuban",
"Municipalities":[
{"id":0,"MunName":"Mun7"},
{"id":1,"MunName":"Mun8"},
{"id":2,"MunName":"Mun9"}
]
}
]
},
{
"id":1,
"StateName":"Badgis",
"Cities":[
{
"id":0,
"CityName":"Denpasar",
"Municipalities":[
{"id":0,"MunName":"Mun1"},
{"id":1,"MunName":"Mun2"},
{"id":2,"MunName":"Mun3"}
]
},
{
"id":1,
"CityName":"Andarab",
"Municipalities":[
{"id":0,"MunName":"Mun4"},
{"id":1,"MunName":"Mun5"},
{"id":2,"MunName":"Mun6"}
]
}
]
}
]
},
{
"id":1,
"CountryName":"India",
"States":[
{
"id":0,
"StateName":"Delhi",
"Cities":[
{
"id":0,
"CityName":"Sonipat",
"Municipalities":[
{"id":0,"MunName":"Mun1"},
{"id":1,"MunName":"Mun2"},
{"id":2,"MunName":"Mun3"}
]
},
{
"id":1,
"CityName":"Rohtak",
"Municipalities":[
{"id":0,"MunName":"Mun4"},
{"id":1,"MunName":"Mun5"},
{"id":2,"MunName":"Mun6"}
]
}
]
},
{
"id":1,
"StateName":"Karnataka",
"Cities":[
{
"id":0,
"CityName":"Mangalore",
"Municipalities":[
{"id":0,"MunName":"Mun1"},
{"id":1,"MunName":"Mun2"},
{"id":2,"MunName":"Mun3"}
]
},
{
"id":1,
"CityName":"Hubli",
"Municipalities":[
{"id":0,"MunName":"Mun4"},
{"id":1,"MunName":"Mun5"},
{"id":2,"MunName":"Mun6"}
]
}
]
}
]
}
]
}
答案 0 :(得分:0)
如果您共享更多代码段,它将更加直观。 顺便说一句,您需要添加一个额外的密钥,以告诉您有关所选选项的信息。
例如 States.states [0] .cities [2] .selected = true
您可以在此处检索所选键并跟踪所选键的值为true。
答案 1 :(得分:0)
您可以根据您在第一个下拉列表中所做的选择以及基于您的选择遍历所选对象的下一个下拉列表来继续更新* ngFor in选项。
对于反应式表单,首先在.ts中导入formGroup和FormControl
ind = 0; // index val of selected drop down
val = 0;
并创建FormGroup实例
myGroup = new FormGroup({
CountryName: new FormControl(),
states: new FormControl(),
Cities: new FormControl(),
});
并在您的HTML中
// data is your json data.
<form [formGroup]="myGroup">
<select formControlName="CountryName" (change)="ind = $event.target.value">
<option *ngFor="let country of data.Countries" [value]="country.id">{{country.CountryName}}</option>
</select>
<select formControlName="states" (change)="val = $event.target.value">
<option *ngFor="let state of data.Countries[ind].States" [value]="state.id">{{state.StateName}}
</option>
</select>
<select formControlName="Cities" (change)="cityVal = $event.target.value">
<option *ngFor="let Cities of data.Countries[ind].States[val].Cities"
[value]="Cities.id">{{Cities.CityName}}
</option>
//...... and so on keep updating your options for all nested array ....
</select>
</form >