Angular 14中ng-select的change事件如何获取完整事件与自定义属性?
解决Angular ng-select change事件无法获取完整选项对象的问题
方案1:将ng-option的value绑定为完整对象
修改前端代码,把ng-option的[value]从op.id改为op,这样change事件会直接返回完整的选项对象,可直接访问自定义属性:
<!-- 修正多余的>,并修改value绑定 --> <ng-select formControlName="constituencyId" placeholder="Select Constituency" (change)='onContituencyChanged($event)'> <ng-option *ngFor="let op of getAllConsituencies" [value]="op" [attr.typename]="op.constituencyTypeName" > {{op.code}} {{op.name}} </ng-option> </ng-select> <label>Constituency Name</label>
后端代码调整:
// 若需要强类型可先定义接口 interface Constituency { id: number; code: string; name: string; constituencyTypeName: string; } onContituencyChanged(selectedItem: Constituency) { // 直接访问完整对象的属性 console.log("选中选区的类型名: ", selectedItem.constituencyTypeName); console.log("选中选区的ID: ", selectedItem.id); // 执行你的业务逻辑 }
方案2:保留value为ID,通过ID查找对应对象
如果formControl需要提交ID,不想修改value绑定,可在change事件中通过返回的ID从数据源里匹配完整对象:
前端代码(仅修正多余的>):
<ng-select formControlName="constituencyId" placeholder="Select Constituency" (change)='onContituencyChanged($event)'> <ng-option *ngFor="let op of getAllConsituencies" [value]="op.id" [attr.typename]="op.constituencyTypeName" > {{op.code}} {{op.name}} </ng-option> </ng-select> <label>Constituency Name</label>
后端代码调整:
onContituencyChanged(selectedId: number) { // 从数据源中查找对应项 const selectedConstituency = this.getAllConsituencies.find(item => item.id === selectedId); if (selectedConstituency) { console.log("选中选区的类型名: ", selectedConstituency.constituencyTypeName); // 执行你的业务逻辑 } }
额外注意
- 原前端代码中ng-select标签末尾有一个多余的
>,需删除避免DOM解析错误。 - 若使用方案1,formControl的值会变成整个对象,提交表单时需提取
selectedItem.id作为constituencyId的提交值。
内容的提问来源于stack exchange,提问作者Hasan Javed
相关产品推荐
相关产品推荐

