动态 Select 选项不具有约束力 Angular 2+

Dynamic Select Option isn't binding Angular 2+

我正在开发一个依赖于另一个选项的 select 选项。在这种情况下,用户 select 国家和这个国家的城市被加载。我在网上看了一些例子,但还是不行。第一个 select 选项运行良好,也就是说,国家列表正确显示。但是第二个,当我select一个特定的国家时,没有显示相关的城市。

查看代码:

<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"} ] 
}]

如果您使用的是 angular2-materialize,我相信您需要添加指令 materializeSelectOptions,否则 materialize 不会跟踪对选项的更改:

<select materialize="material_select" formControlName="city" [materializeSelectOptions]="cities">

至于为什么第一个 select 没有那个就可以工作,不能说。周围是否有 *ngIf="countries"?

附带说明一下,您将类型设置为初始值。应该是:

countries: any[]; // = null
countrySelected: any;
cities: any[];