为什么在< select>< option>中选择了属性不能与ngModel一起使用? [英] Why attribute selected in <select><option> don't work with ngModel?

查看:73
本文介绍了为什么在< select>< option>中选择了属性不能与ngModel一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Angular 6有问题:如果我使用基于<select>元素(组合框)的组件,如果我以经典方式使用它,则一切正常(注意,我使用了selected属性:结果是,在模板中,默认选项已经显示为选中状态,正如我期望的那样!):

I have a problem with Angular 6: if I use a component based on the <select> element (combo-box), if I use it with the classic way, everything works (notice that I used the selected attribute: the result is that in the template the default option already appears as selected, as I would expect!):

<select data-width="200px" title="title" name = "name"
>
  <option value='default' selected>Default</option>
  <option value='1'>Value 1</option>
  <option value='2'>Value 2</option>
</select>

问题是,如果我使用[(ngModel)]指令( 它需要我一定要在组合框中输入值),由于某种原因,所选属性似乎不再起作用,并且组合框显示为空值作为selected选项.

The problem is that if I use the [(ngModel)] directive ( it needs me necessarily to get the value entered in the combo box), for some reason the selected attribute does not seem to work anymore and the combo box appears with an empty value as the selected option.

<select data-width="200px" title="title" name = "name"
        [(ngModel)] = "value"
>
  <option value='default' selected>Default</option>
  <option value='1'>Value 1</option>
  <option value='2'>Value 2</option>
</select>

这当然不是我希望选择保留ngModel指令的默认选项的行为. 我该如何解决这个问题?

This is certainly not the behavior I would like to have a default option selected preserving the ngModel directive. How can I solve this problem?

推荐答案

,因为Angular不依赖selected来检查值.

because Angular doesn't rely on selected to check the value.

ngModel将HTML元素绑定到实际值:如果要默认选择一个值,则ngModel必须等于该值.

ngModel bind your HTML element to an actual value : if you want to select a value by default, your ngModel has to be equal to that value.

因此,在您的组件中,您应该拥有

So, in your component, you should have

value = 'default'; // or '1' or '2'

以便Angular在您的选择中获取正确的选项.

So that Angular fetches the correct option in your select.

这篇关于为什么在&lt; select&gt;&lt; option&gt;中选择了属性不能与ngModel一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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