【发布时间】:2018-09-13 04:25:15
【问题描述】:
我正在开发一个依赖于另一个的选择选项。在这种情况下,用户选择国家,然后加载该国家的城市。我在互联网上查看了一些示例,但仍然无法正常工作。第一个选择选项效果很好,这意味着国家列表正确显示。但是第二个,当我选择一个特定的国家时,没有显示相关的城市。
查看代码:
<div class="input-field col s6 m3 l3">
<select materialize="material_select" formControlName="country" (change)="selectCity($event.target.value)">
<option value="0" disabled selected>Country</option>
<option *ngFor="let c of countries" value={{c.id}}>{{c.name}}</option>
</select>
<label>Country</label>
</div>
<div class="input-field col s6 m3 l3">
<select materialize="material_select" formControlName="city">
<option value="0" disabled selected>city</option>
<option *ngFor="let ci of cities" value={{ci.id}}>{{ci.name}}</option>
</select>
<label>City</label>
</div>
组件代码,总结:
countries = any[];
countrySelected = any;
cities = any[];
this.placeService.getPlaces().subscribe(data => this.countries = data);
selectCity(value) {
this.countrySelected= this.countries.find(o => o.id === value);
this.cities= this.countrySelected.city;
}
位于服务中的方法:
getPlaces() {
return this.http.get('assets/database/rac/places.json')
.map( (res: Response) => res.json().country);
}
最后是调用的JSON文件:
{
"country":
[{
"id": "1",
"name": "Brazil",
"city": [ { "id": "1", "name": "Rio Branco"},
{ "id": "2", "name": "Xapuri"},
{ "id": "3", "name": "Cruzeiro do Sul"} ]
},
{
"id": "2",
"name": "Argentina",
"city": [ { "id": "4", "name": "Buenos Aires"},
{ "id": "5", "name": "Cordoba"},
{ "id": "6", "name": "Rosario"} ]
}]
【问题讨论】:
-
在 stackblitz 中尝试过(删除了样式)似乎在这里工作正常:stackblitz.com/edit/angular-pf1znf 你能更新一下吗?
-
嗨,我已经使用上面的解决方案添加 [materializeSelectOptions]="cities" 并且工作正常!谢谢
标签: angular angular2-forms angular2-directives angular-directive ngfor