默认为Angular2< option>在< select>中具有双向绑定 [英] Defaulting an Angular2 <option> in a <select> with two-way binding
问题描述
我想使用HTML设置默认值<option>
的<select>
,并通过两种方式绑定到模型来填充<select>
的其余部分.
I'd like to setup a <select>
with a default <option>
using HTML, and populating the rest of the <select>
with two way binding to my model.
HTML:
<select class="form-control" required
[(ngModel)]="model.product"
ngControl="product">
<option value="">Select a product</option>
<option *ngFor="#product of products" [value]="product">{{product}}</option>
</select>
型号:
products: string[] = [
'Foo',
'Bar'
];
现在发生的是我的选择绑定到了模型,即:
What's happening now is my the select is binding to the model, which is:
model: Entry = new Entry();
因此,product
属性中没有默认值,因此<select>
绑定为无.我的意思是,这按预期工作.
So, there's no default value in the product
property, thus the <select>
binds to nothing. I mean, this is working as expected.
我试图弄清楚如何在<select>
中显示默认值,并且我希望在不对模型中的UI值进行硬编码并将其默认为新实例的情况下做到这一点.我的模特Angular 2有办法解决吗?
I'm trying to figure out how to get a default value to show up in the <select>
though, and I'd like to do that without hard coding a UI value in my model and defaulting that in a new instance of my model. Does Angular 2 have a way to deal with this?
结果HTML应该如下所示:
The result HTML should look like:
<select>
<option value>Select a product</option>
<option value="foo">Foo</option>
<option value="bar">Bar</option>
</select>
推荐答案
我认为Angular没有办法解决这个问题.您将需要做一些工作:
I don't think Angular has a way to deal with this. You'll have to do some work:
<select class="form-control" required [(ngModel)]="model.product">
<option *ngFor="#product of [defaultStr].concat(products)"
[value]="product === defaultStr ? null : product">
{{product}}
</option>
</select>
defaultStr = 'Select a product';
model = { product: null };
products: string[] = [
'Foo',
'Bar'
];
由于使用NgModel绑定选定值,因此必须首先将bound属性设置为默认值null
,否则默认情况下不会选择该选项:
Since you are using NgModel to bind the selected value, you have to set the bound property to the default value initially, which is null
, otherwise that option won't be selected by default:
model = { product: null };
在null
中,我注意到HTML是
With null
, I noticed that the HTML is
<option value="null">Select a product</option>
因此,您可能更喜欢使用空字符串''
而不是null
:
So, you may prefer to use an empty string ''
instead of null
:
[value]="product === defaultStr ? '' : product"
model = { product: '' };
然后HTML是
<option value="">Select a product</option>
这篇关于默认为Angular2< option>在< select>中具有双向绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!