角度2-如何设置< select>默认选择的选项 [英] angular 2 - how to set <select> default selected option
问题描述
我的模板就是这样
<select>
<option>AM</option>
<option>PM</option>
</select>
如何设置默认情况下选择的AM选项?
How can I set option AM selected by default?
推荐答案
如果您不想动态地执行任何操作,则旧的纯HTML方法仅适用于Angular2:
The old pure HTML way simply works with Angular2, if you do not want to do anything dynamically:
<select>
<option selected>AM</option>
<option>PM</option>
</select>
但是下面是Angular 2方法,它允许您动态分配选定的值,这可能是实际的和常见的用例:(您需要导入FormsModule
)
But the following is the Angular 2 way which allows you to dynamically assign selected value, which may be the practical and common use case: (You need to import FormsModule
)
<select [(ngModel)]='selectedValue'>
<option value='AM'>AM</option>
<option value='PM'>PM</option>
</select>
以及您的组件类
selectedValue = 'AM'; // You may assign 'AM or 'PM' dynamically here
以下链接可能会有用:
https://angular.io/api/forms/NgSelectOption
https://angular.io/api/forms/NgModel
上述Angular 2方法是模板驱动窗体方法.还有另一种方法,这是下面描述的反应形式方法:(您需要导入ReactiveFormsModule
)
The above mentioned Angular 2 method is template driven forms method. There is another way of doing the same which is reactive forms approach described bellow: (You need to import ReactiveFormsModule
)
<select [formControl]='control'>
<option>AM</option>
<option>PM</option>
</select>
以及您的组件类
control = new FormControl('AM');
以下链接可能会有用:
https://angular.io/api/forms/FormControlDirective
这篇关于角度2-如何设置< select>默认选择的选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!