首页 > 解决方案 > 如何在使用 ngModel 的选择元素上设置禁用的默认选项(角度 11)

问题描述

我有一个看起来像这样的选择元素:

 <select (change)="handleEvent($event)">
    <option [value]="null" selected disabled>Select thing</option>
    <ng-container *ngIf="data">
      <ng-container *ngFor="let item of data">
        <option [value]="item.id">{{ item.name }}</option>
      </ng-container>
    </ng-container>
  </select>

请注意,默认选项并非来自动态数据,因此我禁用了它。我想在选择一个选项时访问整个数据对象而不仅仅是 id 所以我这样做了:

 <select [(ngModel)]="selectedItem" (change)="handleItemSelected()">
    <option [value]="null" selected disabled>Select thing</option>
    <ng-container *ngIf="data">
      <ng-container *ngFor="let item of data">
        <option [ngValue]="item">{{ item.name }}</option>
      </ng-container>
    </ng-container>
  </select>

除了在我打开选择框之前禁用的默认选项不再显示之外,这很有效。我做了一些阅读并了解到这是因为默认选择选项变为任何值

selectedItem

是组件初始化的时间,在这种情况下是未定义的。但是,添加

this.selectedItem = {
  name: "Select a thing"
}

也没有填充该字段。我在 init 和构造函数中都试过了。有人知道吗:

1:为什么不填充默认选项
2:如何在仍然使用 ngModel 的同时禁用默认选项

标签: javascriptangulartypescript

解决方案


将 selectedItem 定义为 null,因为该选项的值为 null

selectedItem = null;

在此处输入图像描述


推荐阅读