Angular下拉框默认选项“Choose User Types”不显示问题求助
解决Angular下拉框默认选项不显示问题
问题根源
[(ngModel)]="user_type_id"绑定的变量初始值未设为null,Angular会根据该值自动匹配选中项,覆盖默认选项的selected属性*ngFor循环项中设置的[attr.selected]="i == 0 ? true : null"会强制选中第一个动态生成的选项,和默认选项冲突- Angular中
ngModel的绑定优先级高于原生selected属性,手动设置selected无效
修复步骤
- 初始化ngModel绑定变量:在组件代码中将
user_type_id初始值设为nulluser_type_id: number | null = null; - 移除冲突属性:删除
*ngFor选项里的[attr.selected],让ngModel统一控制选中状态 - 简化默认选项:保留
disabled和[value]="null",无需手动添加selected(当user_type_id为null时会自动选中该选项)
修正后的完整代码
<select class="form-control" id="ddSelectaTopic" onchange="if(this.value==='') {this.style.color='#999'} else {this.style.color='#333'}" [(ngModel)]="user_type_id" (change)="TypeChange($event.target.value,access_id)" [disabled]="access_id == 1 || !access_id"> <option disabled [value]="null">Choose User Types</option> <option *ngFor="let type of UserTypes" [value]="type.id"> <span *ngIf="access_id">{{type.name}}</span> </option> <option value="newType">New User Type</option> </select>
额外提示
如果问题仍存在,检查UserTypes是否在组件初始化阶段就已赋值;若为异步加载,确保加载完成后user_type_id未被意外赋值为非null值。
内容的提问来源于stack exchange,提问作者vince
相关产品推荐
相关产品推荐

