我有像这样的选择下拉列表
<select class="form-control" id="sel1" [(ngModel)]="studentObj.department" name="dept">
<option *ngFor="let dept of departmentList" [ngValue]="dept">{{dept}}</option>
</select>
添加学生时,应将占位符显示为“选择部门”,在编辑学生时,应显示所选值。 我尝试添加
<option value="" disabled="true" [selected]="true">--please select--</option>
但默认情况下它没有被选中。
答案 0 :(得分:2)
您可以通过将<select>
的值设置为与默认studentObj.department
的空字符串(''
)值匹配来设置<option>
的默认值:
<强> TS 强>
export class AppComponent {
studentObj: { [key: string]: any } = {
department: ''
};
departmentList: string[] = [
'foo',
'bar',
'foobar'
];
}
<强> HTML 强>
<select class="form-control" id="sel1" [(ngModel)]="studentObj.department" name="dept">
<option value="" disabled="true">--please select--</option>
<option *ngFor="let dept of departmentList" [ngValue]="dept">{{dept}}</option>
</select>
以下是显示此功能的example。这将有效地与Reactive Forms一起使用,并且在创建FormControl
元素时初始化默认值。此方法适用于标准的跨浏览器<select>
/ <option>
元素,而不依赖于第三方库。
注意:如果您的ngValue
只是一个字符串数组,则可能不需要departmentList
。如果ngValue
中的每个部门都是对象,则只需要departmentList
。如果它是一个对象,您可能需要将dept
占位符变量中的特定属性定位到*ngFor
中,以获取每个属性的显示文本。
希望这有帮助。
答案 1 :(得分:0)
使用占位符很简单,我使用Angular2材质, 所以它是这样的:
<md-select placeholder="--please select--">
<md-option *ngFor="let dept of departmentList" [ngValue]="dept">{{dept}} </md-option>
</md-select>
它按预期工作。
答案 2 :(得分:0)
这是我实施的方式,
initializeSelectOptions(){
this.optionList = ['..' , '..' , '..'
];
this.optionList.unshift('Select Options')
}
ngOnInit(){
this.initializeSelectOptions();
}
在模板中:
<select class='select-option' required [(ngModel)]='optionSelected' (ngModelChange)='optionChanged($event)'>
<option class='option' *ngFor='let option of optionList' [value]="option " [disabled]="option === 'Select Options'">{{option}}</option>
</select>