Angular2使用ngValue选择初始对象 [英] Angular2 select initial object with ngValue

查看:70
本文介绍了Angular2使用ngValue选择初始对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在填充选择时设置初始值,数据来自其余部分并已加载到组件中.

I'm trying to set an initial value when filling a select, the data is coming from rest and loaded in the component. The initial value is not set/updated after the

获取列表以填充选择内容:

Getting the list to fill the select:

...
ngOnInit():any {

this.crudService.get(`/api/countries`).subscribe(data => {this.countries = data;});
...

让模型对象拥有一个国家/地区:

Getting the model object witch has a Country:

...
this.crudService.get('/api/unions/default').subscribe(data => {
 this.union = data;
...

HTML:

...
<div class="col-md-2">
              <select *ngIf="union.country" [(ngModel)]="union.country" class="form-control">
                <option *ngFor="let c of countries" [ngValue]="c">{{c.code}}</option>
              </select>
            </div>

...

一切正常,我可以选择一个国家,并且该模型在模型中已正确更新,但是未选择初始值,但模型中存在初始值... 有任何建议还是这是一个错误?

Everything works, I can select a country and it is correctly updated in the model but the initial value is not selected but existing in the model... Any suggestions or is this a bug?

谢谢!

推荐答案

如果将默认值分配给union.country且它是一个对象(相对于原始值),则它必须是相同的实例,而不仅仅是具有相同内容的对象.

If the default value is assigned to union.country and it is an object (vs a primitive value), it needs to be the same instance, not only an object with the same content.

这篇关于Angular2使用ngValue选择初始对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆