Angular2选择ngValue为null [英] Angular2 select with ngValue null
问题描述
这是我要执行的操作:我希望将选择列表绑定到具有ngValue的对象数组,但是第一个选项必须是具有null
值的无"选项.
Here's what I'm trying to do: I want a select list bound to an array of objects with ngValue, but the first option needs to be a "None" option with a null
value.
型号:
this.managers = [
{ id: null, name: "(None)" },
{ id: 1, name: "Jeffrey" },
{ id: 2, name: "Walter" },
{ id: 3, name: "Donnie" }
];
this.employee = {
name: "Maude",
managerId: null
};
查看:
<select [(ngModel)]="employee.managerId">
<option *ngFor="#manager of managers" [ngValue]="manager.id">{{ manager.name }}</option>
</select>
在加载时,列表正确绑定到"None"元素.但是,如果您更改为其他项目并返回,则模型值现在会切换为字符串0: null
.这很不方便.这意味着我必须先拦截该值并将其手动更改为null,然后再尝试将其保存到服务器.
On load, the list correctly binds to the "None" element. But if you change to a different item and back, the model value now switches to a string of 0: null
. This is pretty inconvenient; it means I have to intercept the value and change it to a null manually before I attempt to save it to the server.
这是一个带有演示的插件: http://plnkr.co/edit/BH96RWZmvbbO63ZAxgNX?p=preview
Here's a Plunker with a demo: http://plnkr.co/edit/BH96RWZmvbbO63ZAxgNX?p=preview
这在Angular 1中很容易完成,只需加上一个<option value="">None</option>
This was pretty easily done in Angular 1 with an extra <option value="">None</option>
这似乎是很常见的情况,但是我一直找不到任何解决方案.我也尝试添加<option [ngModel]="null">None</option>
,但是结果却是相同的0: null
值.
This seems like it would be a pretty common scenario, and yet I've been unable to find any solutions. I've also tried adding an <option [ngModel]="null">None</option>
, but it results in the same 0: null
value.
有什么建议吗?
推荐答案
对我来说,这确实像是个错误,但是如果您正在寻找快速的解决方案,则可以将null
标识符简单地转换为string
.它应该可以解决问题,但是您应该做一些额外的动作才能使它起作用.
For me it is really looks like a bug, but I if you are looking for fast solution, you can simply convert null
identifier to string
. It should solve the problem but you should do some additional moves to make that work.
请参阅示例 Plnkr示例
或者,如果您要按照ng1中提到的方式进行操作, 您可以这样做: Plnkr示例
Or if you are going to do that in the way you mention from ng1, you can do like this: Plnkr example
我知道这不是最好的解决方案,但是希望在NG团队修复此错误之前能对您有所帮助!
I know that it is not best solution, but hope will help you before this bug will be fixed by NG team!
- https://github.com/angular/angular/issues/10349
- https://github.com/angular/angular/pull/12026
这篇关于Angular2选择ngValue为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!