我的模板中有以下代码:
<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做到这一点?
我的解决方案:
在组件打字稿文件中,我添加了一个我未初始化的属性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>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句