javascript - 如何在使用 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 的同时禁用默认选项
解决方案
推荐阅读
- javascript - 从字符串数组中获取最大值/最小值(javascript)
- python - 计算中位数的自定义函数(带字符串)
- asp.net - 设置 GridView 的 EditIndex 会使 EditItemTemplate 中的元素不更新
- c# - 对类型 system.icloneable' 的引用声称它在 system.runtime 中定义但无法找到
- javascript - angularjs 承诺/超时:条件超时
- angular6 - 反应式表单 - 在提交时,检查表单中是否至少有一项更改,然后才调用 API
- ionic4 - Ionic 4 迁移:IonicModule 更改
- javascript - setTimeout() 跳转到数组的最后一个元素我该如何防止这种情况?
- mysql - 我需要在下面的 sql 查询中使用什么类型的连接来检索正确的结果?
- node.js - 服务器端渲染和生成缓存的 index.html(Vuejs、Nodejs)