我的模板中有这个代码:
<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执行此操作?
答案 0 :(得分:30)
我的解决方案:
在组件样本文件中,我添加了一个我没有初始化的属性selectUndefinedOptionValue,在html中我将undefinedSelectOptionValue添加为占位符选项的值。此解决方案适用于数字和字符串模型属性。
@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>
答案 1 :(得分:11)
我有同样的问题,我在这个很棒的网站上找到了一个例子:Angular Quick Tip
另外,我举了下面的例子:
~
也适用于Reactive Forms,这就是我正在使用的:
// template
<form #f="ngForm">
<select name="state" [ngModel]="state">
<option [ngValue]="null">Choose a state</option>
<option *ngFor="let state of states" [ngValue]="state">
{{ state.name }}
</option>
</select>
</form>
//component
state = null;
states = [
{name: 'Arizona', code: 'AZ'},
{name: 'California', code: 'CA'},
{name: 'Colorado', code: 'CO'}
];
感谢Netanel Basal提供答案
答案 2 :(得分:6)
添加空选项并设置为&#39; undefined&#39;也可以添加空值
<select [(ngModel)]="barcode">
<option value="undefined" disabled selected hidden>Select</option>
<option value="null" disabled selected hidden>Select</option>
<option *ngFor="let city of turkiye" [ngValue]="city.id">{{city.name}}</option>
</select>
答案 3 :(得分:5)
试试这段代码:
<select [ngModel]="selectedSubSectionId? selectedSubSectionId : ''" (ngModelChange)="onSubSectionChange($event)">
<option value="" disabled selected hidden>Placeholder</option>
<option *ngFor="let subSection of event.subSections" [value]="subSection.id">{{ subSection.name }}</option>
</select>
答案 4 :(得分:-4)
您是否尝试将placeholder="Your placeholder string"
置于select或option标记内?
如果您不想在视图中对字符串进行硬编码,我认为字符串可以替换为变量。