如何在Angular 2的select控件中显示占位符(空选项)? [英] How to show placeholder (empty option) in select control in Angular 2?
本文介绍了如何在Angular 2的select控件中显示占位符(空选项)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的模板中有以下代码:
I have this code in my template:
<select [ngModel]="selectedSubSectionId" (ngModelChange)="onSubSectionChange($event)">
<option *ngFor="let subSection of event.subSections" [ngValue]="subSection.id">{{ subSection.name }}</option>
</select>
在我的组件中:
public selectedSubSectionId: any;
public onSubSectionChange(subSectionId: any) {
// some code I execute after ngModel changes.
}
这很好,但是一开始我有一个空盒子。我想在那里显示一个占位符消息。 如何使用ngModel做到这一点?
This works ok, but at the beginning I have an empty box. I want to show a placeholder message there. How can I do this using ngModel?
推荐答案
我的解决方案:
在组件打字稿文件中,添加未初始化的属性selectUndefinedOptionValue,在html中,将undefinedSelectOptionValue添加为占位符选项的值。此解决方案适用于数字和字符串模型属性。
In the component typescript file I add a property selectUndefinedOptionValue that I don't initialize and in the html I add the undefinedSelectOptionValue as value of the placeholder option. This solution works for both number and string model properties.
@Component({
selector: 'some-component-selector',
templateUrl:'url to template',
})
export class SomeComponent implements OnInit {
private selectUndefinedOptionValue:any;
private someObject:SomeObject;
ngOnInit() {
someObject = new SomeObject();
}
}
<select [(ngModel)]="someObject.somePropertyId">
<option disabled hidden [value]="selectUndefinedOptionValue">-- select --</option>
<option *ngFor="let option of options" [value]="option.id">option.text</option>
</select>
这篇关于如何在Angular 2的select控件中显示占位符(空选项)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文