Angular编辑模式下如何获取下拉框值计算ExistingBalance?
解决方案
1. 确保调用getAndSetOpenCreditTrans()前拿到有效的selectedAccountId
因为表单数据加载是异步请求,必须把getAndSetOpenCreditTrans()放在异步请求的subscribe回调内部,等patchValue执行完成后再调用,避免因异步时序问题导致取值为空。
示例代码:
ngOnInit() { // 加载数据库数据的异步请求 this.dataService.getCreditTransaction().subscribe((x) => { // 先完成表单数据填充 this.creditTransactionForm.patchValue(x); // 此时表单已赋值,在这里获取accountId并调用计算方法 this.selectedAccountId = this.creditTransactionForm.get('accountId')?.value; this.getAndSetOpenCreditTrans(); }); }
2. selectedAccountId的赋值方案
a. 赋值位置
- 编辑模式:在异步请求的
subscribe回调里,执行完patchValue后立即赋值,保证表单数据已完全填充。 - 新增模式:保留原有的下拉框
change事件赋值逻辑即可。
b. 从禁用下拉框获取值的方式
直接通过表单控件实例的value属性获取,无需依赖DOM操作或change事件:
// 假设下拉框的formControlName为accountId this.selectedAccountId = this.creditTransactionForm.get('accountId')?.value;
也可以直接从后端返回的数据源x中提取,无需经过表单:
this.selectedAccountId = x.accountId;
内容的提问来源于stack exchange,提问作者jAntoni
相关产品推荐
相关产品推荐

