Why attribute selected in <select><option> don't work with ngModel?

懵懂的女人 提交于 2019-12-24 18:43:43

问题


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>

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>

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?


回答1:


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

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'

So that Angular fetches the correct option in your select.



来源:https://stackoverflow.com/questions/53630274/why-attribute-selected-in-selectoption-dont-work-with-ngmodel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!