动态选择选项不是绑定Angular 2+

时间:2018-04-03 18:31:15

标签: angular angular2-forms angular2-directives angular-directive ngfor

我正在开发一个依赖于另一个的选择选项。在这种情况下,用户选择国家,并在加载此国家/地区的城市之后。我在互联网上看了一些例子,但它仍然没有用。第一个选择选项运作良好,这意味着,国家列表正确显示。但是第二个,当我选择一个特定的国家时,并没有显示相关的城市。

查看代码:

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

1 个答案:

答案 0 :(得分:1)

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

<select materialize="material_select" formControlName="city" [materializeSelectOptions]="cities">
至于为什么没有那个的第一个选择工作,不能说。所有这些都有* ngIf =“国家”吗?

作为旁注,您将类型设置为初始值。应该是:

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