Angular9中select组件无法获取选中值的问题排查
解决Angular 9模态框中Select组件绑定undefined的问题
嘿,我看你在Angular 9项目里用模态框提交数据时,select组件的选中值一直返回undefined,这个问题我之前也遇到过,咱们一步步来排查修复:
问题根源分析
你的代码里有几个关键的语法和绑定错误,导致select的值无法正确同步到TS变量:
- 双向绑定语法错误:你把Angular双向绑定的
[(ngModel)]写成了([ngModel]),顺序反了就没法完成双向绑定。 - Option值绑定错误:你给option的
[value]绑定了字符串'item',而不是你需要的item.id,这导致选中后根本没拿到正确的id值。 - 绑定属性不匹配:HTML里select绑定的是
newItemEditor.productType,但TS代码里你要使用的是productTypeId,属性名不对应自然拿不到值。
修正后的代码
修正后的HTML部分
<div class="modal-body"> <div class="form-group"> <label for="title">Title</label> <input type="text" class="form-control" id="name" placeholder="Item name..." [(ngModel)]="newItemEditor.name" [ngClass]="{ 'is-invalid': newItemEditor.error }" (keyup.enter)="addItem()" /> <div *ngIf="newItemEditor.error" class="invalid-feedback"> {{ newItemEditor.error }} </div> </div> <div class="form-group"> <label for="productType">Product Type</label> <!-- 修正1:把([ngModel])改成[(ngModel)];修正2:绑定到productTypeId;修正3:option的value绑定item.id --> <select class="form-control" [(ngModel)]="newItemEditor.productTypeId"> <option [value]="item.id" *ngFor="let item of productTypeVm.lists"> {{item.name}} </option> </select> </div> </div>
可选的TS优化
你可以给newItemEditor初始化时加上productTypeId属性,让数据结构更清晰:
newItemEditor: any = { name: '', productTypeId: null, error: '' };
额外注意事项
- 确保
productTypeVm.lists在模态框打开前已经成功从接口获取到数据(你当前的代码里在构造函数订阅了接口,这没问题,但如果接口返回慢,模态框打开时select可能为空,也会导致值无法绑定)。 - 提交数据时,
addItem()里的console.log(this.newItemEditor.productTypeId)现在应该能正确打印出选中项的id了。
内容的提问来源于stack exchange,提问作者Danijel Boksan
相关产品推荐
相关产品推荐

