Angular开发中如何获取Dropdown下拉框选中项的id与value
解决方案
你在[ngValue]中已经存储了包含id和名称的完整对象,无需使用原生DOM操作取值,用Angular自带的双向绑定即可直接获取两个值,操作步骤如下:
1. 先确认依赖导入
在你当前组件所属的模块文件(通常是app.module.ts)中确认已导入FormsModule,否则ngModel绑定会失效:
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; // 需导入这个模块 import { AppComponent } from './app.component'; @NgModule({ declarations: [AppComponent], imports: [BrowserModule, FormsModule], // 加入FormsModule bootstrap: [AppComponent] }) export class AppModule { }
2. 修改HTML模板,新增双向绑定
给select标签添加[(ngModel)]绑定组件内的变量:
<div class="form-group"> <label>Item</label> <select id='itemCode' name="itemCode" class="form-control" [(ngModel)]="selectedItem"> <option value="" disabled selected>Choose Item</option> <option *ngFor="let itemValue of itemslistvalue" [ngValue]="{id: itemValue.itemCode, name: itemValue.itemName}"> {{itemValue.itemName}} </option> </select> </div> <div class="form-group"><br> <button type="button" (click)="add()" style=" margin-left:10px;">提交</button> </div>
3. 修改TS组件代码
先声明绑定变量,再在add方法中直接从变量取值即可:
// 组件类中先声明双向绑定对应的变量 selectedItem: {id: string | number, name: string} = null; add() { // 校验是否选中有效选项 if (this.selectedItem?.id && this.selectedItem?.name) { const itemCode = this.selectedItem.id; const itemName = this.selectedItem.name; this.newDynamic = { itemCode: itemCode, ItemName: itemName }; console.log(this.newDynamic); this.dynamicArray.push(this.newDynamic); // 可选:选中后重置下拉框状态 this.selectedItem = null; return true; } // 可自行补充未选中时的提示逻辑 }
原方法失效原因说明
原生DOM的value属性只能读取字符串类型的值,你用[ngValue]存储的对象是Angular框架内部维护的状态,不会直接暴露在DOM属性上,所以用document.getElementById的方式无法拿到完整对象。
内容的提问来源于stack exchange,提问作者Shashi
相关产品推荐
相关产品推荐

