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

查看:24
本文介绍了为什么在 <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 属性似乎不再起作用,组合框显示为空值作为 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天全站免登陆