【问题标题】:Setting selected option of select control in an Angular 2 model-driven form在 Angular 2 模型驱动表单中设置选择控件的选定选项
【发布时间】:2017-04-20 03:56:12
【问题描述】:

我在 SO 和其他地方研究了许多类似的现有答案,但找不到解决方案。

我正在使用 Angular 2 中的模型驱动方法来构建我的表单,它既是添加表单又是编辑表单。在编辑模式下,这些值由从服务中检索到的数据填充:这方面很好,因为简单的文本输入都正确绑定。

其中一个属性是“Country”,这是一个对象,如下所示:

    export class Country {id: number; name: string;}

我想将此绑定到一个选择控件,该控件将具有可用的国家列表,以及在表单加载时填充的模型中的一个。我希望绑定的值是国家对象,而不仅仅是 id。

这里是选择控件的html:

    <select class="form-control" id="country" formControlName="country">
          <option value="default">--Select a country--</option>
          <option *ngFor="let c of countries" [value]="c">{{c.name}}      </option>
</select> 

这是我尝试从组件类中填充值的地方:

    (<FormControl>this.personForm.controls['country'])
 .setValue(this.person.country, { onlySelf: true });

但是当页面加载时没有选择选项,即使控制台确认 this.person.country 存在并且填充了正确的对象。

我可以让它与 ids 一起工作:在视图中更改为 [value]="c.id" 并在类中附加 .id,然后它在选择正确的选项时起作用。问题是 select 不再为 country 属性发出一个对象,而只是 id。我尝试将 [value] 更改为 [ngValue] 并得到相同的结果。我什至将 [ngModel]="country" 添加到 select 元素中,但这也无济于事。

如果有任何帮助,我将不胜感激。

【问题讨论】:

    标签: html angular


    【解决方案1】:

    问题很可能是this.person.countrycountries 数组中的country 不同。

    如果我们想让它们相同,我们可以显式订阅选择控件的valueChanges 或将[(ngModel)] 绑定到person.country

    订阅更改

    代码

    this.countryForm.controls['country'].valueChanges.subscribe(country => 
      this.person.country = country;
    );
    
    // initialize by finding the correct country object (this will overwrite the person's country object)
    this.countryForm.controls['country'].setValue(countries.filter(c => c.id === person.country.id));
    

    模板

    ngModel 绑定

    我们仍然必须使对象匹配(比较 Angular 2 使用的策略,这实际上是 JS 使用的)

    代码

    this.person.country = this.countries.filter(c => c.id === this.person.country.id)[0];
    

    模板

    <select class="form-control" id="country" formControlName="country" [(ngModel)]="person.country">
        <option value="default">--Select a country--</option>
        <option *ngFor="let c of countries" [ngValue]="c">{{c.name}}</option>
    </select>
    

    ngModel Plunker: http://plnkr.co/edit/UIS2V5rKh77n4JsjZtii?p=preview

    订阅 Plunkerhttp://plnkr.co/edit/yyZ6ol1NPD77nyuzwS2t?p=info

    【讨论】:

    • 做到了!非常感谢你的帮助。我永远不会在过滤器末尾得到 [0] - 这是为了返回匹配的第一个值吗?
    • 是的,它是第一个值,但理论上 ID 是唯一的,所以我希望只有一个。
    • @silentsod,你知道如何设置和显示--Select a country--作为默认值吗?
    • 我认为 formControlName(反应式表单)和 ngModel 没有混合在一起。
    • 我不知道 Angular 在 2016 年的状态,但是对于 v4+ ngValue 和 ngModel 已经不适用了。这是我用来选择默认值的方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-02
    • 1970-01-01
    • 2017-10-05
    • 2017-02-05
    • 2018-09-13
    • 1970-01-01
    相关资源
    最近更新 更多