Angular动态FormArray使用CVA,子验证未传播。
创始人
2024-10-24 14:31:12
0

在Angular中,可以使用ControlValueAccessor(CVA)来创建自定义表单控件,并实现表单验证。当使用动态FormArray时,可能会遇到子验证未传播的问题。下面是一个解决方法的示例代码:

首先,创建一个自定义表单控件,并实现ControlValueAccessor接口:

import { Component, forwardRef, Provider } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';

const CUSTOM_VALUE_ACCESSOR: Provider = {
  provide: NG_VALUE_ACCESSOR,
  useExisting: forwardRef(() => CustomFormComponent),
  multi: true
};

@Component({
  selector: 'app-custom-form',
  template: `
    
`, providers: [CUSTOM_VALUE_ACCESSOR] }) export class CustomFormComponent implements ControlValueAccessor { formArray: FormArray; // Implement ControlValueAccessor methods writeValue(value: any): void { if (value) { this.formArray = new FormArray(value); } else { this.formArray = new FormArray([]); } } registerOnChange(fn: any): void { this.formArray.valueChanges.subscribe(fn); } registerOnTouched(fn: any): void {} setDisabledState(isDisabled: boolean): void {} }

然后,在父组件中使用该自定义表单控件,并传入动态的FormArray:

import { Component } from '@angular/core';
import { FormBuilder, FormGroup, FormArray } from '@angular/forms';

@Component({
  selector: 'app-parent-component',
  template: `
    
` }) export class ParentComponent { form: FormGroup; constructor(private fb: FormBuilder) { this.form = this.fb.group({ customFormArray: this.fb.array([]) }); } // Add a new control to the FormArray addControl(): void { const customFormArray = this.form.get('customFormArray') as FormArray; customFormArray.push(this.fb.control('')); } }

在父组件中,每当添加新的控件时,调用addControl()方法。这样,动态的FormArray会传播到自定义表单控件中,子验证也会正确工作。

希望这个示例能够帮助你解决Angular动态FormArray使用CVA时子验证未传播的问题。

相关内容

热门资讯

透视软件!aapoker透视方... 透视软件!aapoker透视方法(透视)透视插件(切实真的是有挂)1、aapoker透视方法系统规律...
透视计算!德扑圈透视(透视)透... 透视计算!德扑圈透视(透视)透视(确实是真的有挂)1、打开软件启动之后找到中间准星的标志长按。2、然...
透视代打!aapoker怎么设... 透视代打!aapoker怎么设置抽水(透视)免费透视脚本(原来存在有挂);1、aapoker怎么设置...
透视安卓版!德普辅助器辅助器怎... 透视安卓版!德普辅助器辅助器怎么用(透视)透视(好像真的是有挂)1、游戏颠覆性的策略玩法,独创攻略技...
透视辅助!aapoker能控制... 透视辅助!aapoker能控制牌吗(透视)辅助插件工具(果然是有挂)1、该软件可以轻松地帮助玩家将a...
透视攻略!德普之星透视(透视)... 透视攻略!德普之星透视(透视)私人局透视(其实真的是有挂)运德普之星透视辅助工具,进入游戏界面。进入...
透视私人局!aapoker辅助... 透视私人局!aapoker辅助怎么用(透视)插件下载(本来是有挂)1)aapoker辅助怎么用辅助挂...
透视了解!德普之星透视(透视)... 透视了解!德普之星透视(透视)透视(果然存在有挂)1、该软件可以轻松地帮助玩家将德普之星透视透视辅助...
透视安装!aapoker真的假... 透视安装!aapoker真的假的(透视)透视插件(真是是有挂);1、下载好aapoker真的假的辅助...
透视讲解!德普辅助器辅助器怎么... 透视讲解!德普辅助器辅助器怎么用(透视)辅助器app(都是是有挂)1、德普辅助器辅助器怎么用ai机器...