gpt4 book ai didi

html - 在 Angular 2 模型驱动表单中设置选择控件的选定选项

转载 作者:技术小花猫 更新时间:2023-10-29 12:27:16 25 4
gpt4 key购买 nike

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

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

其中一个属性是“国家/地区”,这是一个对象,如下所示:

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

我想将其绑定(bind)到一个选择控件,该控件将包含可用的国家/地区列表,以及在加载表单时填充的模型中的国家/地区列表。我希望绑定(bind)的值是国家对象,而不仅仅是 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 一起工作:在 View 中更改为 [value]="c.id"并在类中附加 .id,然后它会在选择正确的选项时起作用。问题是 select 不再为 country 属性发出一个对象,只是 id。我尝试将 [value] 更改为 [ngValue] 并得到相同的结果。我什至将 [ngModel]="country"添加到 select 元素,但这也没有帮助。

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

最佳答案

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

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

订阅更改

代码

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 绑定(bind)

我们仍然需要使对象匹配(比较 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 插件: http://plnkr.co/edit/UIS2V5rKh77n4JsjZtii?p=preview

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

关于html - 在 Angular 2 模型驱动表单中设置选择控件的选定选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40979640/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com