加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

如何在Angular 2中的选择控件中显示占位符(空选项)?

发布时间:2020-12-17 07:55:50 所属栏目:安全 来源:网络整理
导读:我在我的模板中有这个代码: select [ngModel]="selectedSubSectionId" (ngModelChange)="onSubSectionChange($event)" option *ngFor="let subSection of event.subSections" [ngValue]="subSection.id"{{ subSection.name }}/option/select 在我的组件中:
我在我的模板中有这个代码:
<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执行此操作?

我的解决方案

在组件typescript文件中,我添加了一个我没有初始化的属性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>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读