【问题标题】:Dynamic Select Option isn't binding Angular 2+动态选择选项不绑定 Angular 2+
【发布时间】: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


【解决方案1】:

如果你使用angular2-materialize,我相信你需要添加指令materializeSelectOptions,否则materialize不会跟踪选项的变化:

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

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

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

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

【讨论】:

  • 我的朋友,你拯救了我的一天。我添加了这个 [materializeSelectOptions]="cities" 并且工作正常。我真的很感激你的关注
  • 乐于助人:)
猜你喜欢
  • 1970-01-01
  • 2018-02-28
  • 2017-10-28
  • 2017-12-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-27
  • 1970-01-01
相关资源
最近更新 更多