Angular 10中ng-select绑定值返回undefined及表单清除失效问题
Angular 10 ng-select 问题解决方案
问题1:下拉框绑定值返回undefined
你的代码存在变量混淆与取值逻辑错误:
selectedConnection是ng-select的下拉选项数据源数组,但你在onSubmit中试图通过this.selectedConnection.value获取选中值——数组本身不存在value属性,必然返回undefined。- 由于ng-select已绑定
formControlName="ConnectionType",正确的选中值应从表单控件中读取:
修改onSubmit里的body构造逻辑:
let body = { ConnectionType: this.collectionManagementForm.get('ConnectionType').value || '' };
建议重命名数据源变量以避免混淆,比如将selectedConnection改为connectionOptions,同步更新HTML:
<ng-select [items]="connectionOptions" [closeOnSelect]="true" bindValue="id" placeholder="Select" bindLabel="name" formControlName="ConnectionType" >
问题2:表单清除功能无效
你的restForm方法逻辑冲突:先调用this.collectionManagementForm.reset(),随后又通过clearForm()重新创建FormGroup,导致原表单引用被替换,ng-select绑定的旧控件无法响应重置操作。
修改重置逻辑,移除重复创建表单的代码:
restForm() { this.popUpTittle = 'Add'; this.IsSubmitted = false; document.getElementById('btnUpdate').innerText = 'Add'; // 直接重置现有表单控件值 this.collectionManagementForm.reset({ ConnectionType: '' }); } // 移除clearForm方法,无需重复创建表单
若需保留表单初始化逻辑,仅在组件初始化时调用一次即可:
ngOnInit() { this.initForm(); } initForm() { this.collectionManagementForm = this.fb.group({ ConnectionType: [''] }); } restForm() { this.popUpTittle = 'Add'; this.IsSubmitted = false; document.getElementById('btnUpdate').innerText = 'Add'; this.collectionManagementForm.reset({ ConnectionType: '' }); }
额外说明:HTML中的自定义模板用法不符合ng-select规范,会导致选中项显示异常。若无需自定义模板,直接删除该模板代码;若需自定义,参考正确写法:
<ng-select [items]="connectionOptions" [closeOnSelect]="true" bindValue="id" placeholder="Select" bindLabel="name" formControlName="ConnectionType" > <!-- 正确的选项模板示例 --> <ng-template ng-option-tmp let-item="item"> {{item.name}} </ng-template> </ng-select>
内容的提问来源于stack exchange,提问作者Kuldip Baldaniya
相关产品推荐
相关产品推荐

