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

查看:24
本文介绍了选择列表设置所选项目角度 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).

问题是 selected 属性不起作用,而我的 select 没有转到正确的角色.我做错了什么?

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.rolengModel 将使匹配的项目成为选定的项目.

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

如果 role 是一个对象,则分配的实例需要相同.

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

另见最近添加的自定义比较https://github.com/angular/angular/问题/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;
}

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

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