Angular应用中使用concat合并FormGroup失效问题求助
解决Angular ReactiveForms动态控件不生效问题
问题根源
- 操作逻辑错误:你需要为选中的单个account(FormGroup类型)添加alternate前缀控件,而非往accounts(FormArray类型)里新增新的account条目
- 方法使用错误:
concat是JS数组原生方法,仅会返回新数组,既不会修改原FormArray的controls属性,也不会触发ReactiveForms的变更检测,无法实现控件新增效果 - 存在基础语法错误:ngOnInit生命周期中误将
addAccount()调用写进了formBuilder.group()的配置对象内部,createAlternateAccountForm()方法缺少闭合括号,会直接导致代码运行异常
修正代码
组件逻辑修正
accounts: FormArray; ngOnInit(): void { // 修正group配置的语法错误 this.formGroup = this.formBuilder.group({ accounts: this.formBuilder.array([]), bankContactName: [ { value: null, disabled: this.readonly }, requiredIfValidator(() => this.form && this.form.accounts.value.length > 0 && this.requiredSection) ], bankContactPhone: [ { value: null, disabled: this.readonly }, requiredIfValidator(() => this.form && this.form.accounts.value.length > 0 && this.requiredSection) ] }); this.addAccount(); this.accounts = this.formGroup.get('accounts') as FormArray; } addAccount() { this.accounts.push(this.createAccountForm()); } createAccountForm(): FormGroup { const accountGroup = this.formBuilder.group( { yesNoMultilingual: [{ value: false, disabled: this.readonly }], bankAccountPurpose: [{ value: null, disabled: this.readonly }, requiredIfValidator(() => this.requiredSection)], bankName: [{ value: null, disabled: this.readonly }, requiredIfValidator(() => this.requiredSection)], } ); // 直接给当前account的单选控件加值变化监听,不用全局监听FormArray accountGroup.get('yesNoMultilingual').valueChanges .pipe(takeUntil(this.notifier$)) .subscribe(isSelectYes => { if (isSelectYes) { // 给当前account FormGroup添加alternate控件 const alternateControls = this.createAlternateAccountForm().controls; Object.keys(alternateControls).forEach(key => { if (!accountGroup.contains(key)) { accountGroup.addControl(key, alternateControls[key]); } }); } else { // 选否的时候移除对应控件,避免冗余 ['alternateBankAccountPurpose', 'alternateBankName'].forEach(key => { if (accountGroup.contains(key)) { accountGroup.removeControl(key); } }); } }); return accountGroup; } createAlternateAccountForm(): FormGroup { return this.formBuilder.group( { alternateBankAccountPurpose: [{ value: null, disabled: this.readonly }, requiredIfValidator(() => this.form.yesNoMultilingual?.value === true)], alternateBankName: [{ value: null, disabled: this.readonly }, requiredIfValidator(() => this.requiredSection)], } ); }
模板调整说明
原有模板逻辑无需修改,你已经为alternate控件外层加了*ngIf="accounts.controls[i].get('yesNoMultilingual')?.value"判断,只要FormGroup内存在对应控件就不会抛出找不到控件的错误。
内容的提问来源于stack exchange,提问作者Tom
相关产品推荐
相关产品推荐

