选择列表设置选择的项目angular 2 ngModel [英] select list set selected item angular 2 ngModel

查看:74
本文介绍了选择列表设置选择的项目angular 2 ngModel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我当前的代码:

<select name="role" [(ngModel)]="user.role">
    <option *ngFor="let role of roles" [ngValue]="role" [attr.selected]="role == user.role ? 'true' : 'false'">{{role.name}}</option>
</select>

我正在加载数组中的所有角色,并且用户类具有Role属性(不是像 user.role = roles [0] 那样加载,而是通过后端数据加载。)

I'm loading all the roles in an array, and the user class has a Role attribute (which is not loaded like user.role = roles[0] but just through the backend data).

问题是所选属性不起作用,而我的选择没有正确的角色。我在做什么错了?

The problem is that the selected attribute is not working, and my select is not going to the correct role. What am I doing wrong?

推荐答案

只需删除

[attr.selected]="role == user.role ? 'true' : 'false'"

并将所选角色分配给 user.role ngModel 将使匹配项成为选定项。

and assign the selected role to user.role and ngModel will make the matching item the selected one.

如果角色是一个对象,则分配的实例必须相同。

If the role is an object, the assigned instance needs to be identical.

另请参见最近添加的自定义比较 https://github.com/angular/angular/issues/13268
自4.0.0-beta.7起可用 >

See also the recently added custom comparison https://github.com/angular/angular/issues/13268 available since 4.0.0-beta.7

<select [compareWith]="compareFn" ...





compareFn(val1, val2): boolean {
  return val1 && val2 ? val1.id === val2.id : val1 === val2;
}

这篇关于选择列表设置选择的项目angular 2 ngModel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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