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时子验证未传播的问题。

相关内容

热门资讯

揭秘攻略!智星菠萝德州辅助挂多... 揭秘攻略!智星菠萝德州辅助挂多功能透视工具,总是是真的有挂(有挂方针)1、每一步都需要思考,不同水平...
一起来探讨!红龙poker辅助... 一起来探讨!红龙poker辅助挂多功能透视工具,一直是有挂(有挂方法)1.红龙poker 选牌创建新...
终于清楚!wepoker辅助挂... 终于清楚!wepoker辅助挂多功能透视工具,竟然有挂(有挂分享)wepoker能透视中分为三种模型...
一分钟揭秘!微扑克辅助挂多功能... 一分钟揭秘!微扑克辅助挂多功能透视工具,竟然是真的有挂(有人有挂)1、打开软件启动之后找到中间准星的...
科技揭秘!wpk辅助挂多功能透... 科技揭秘!wpk辅助挂多功能透视工具,确实是真的有挂(有挂解惑)1、实时wpk透视辅助更新:用户可以...
让我来分享经验!红龙poker... 让我来分享经验!红龙poker辅助挂多功能透视工具,好像存在有挂(有挂规律)亲,关键说明,红龙pok...
关于!wepoker辅助挂多功... 关于!wepoker辅助挂多功能透视工具,好像有挂(存在有挂)1、每一步都需要思考,不同水平的挑战w...
重大通报!wepoker辅助挂... 重大通报!wepoker辅助挂多功能透视工具,真是真的是有挂(果真有挂)在进入wepoker软件靠谱...
查到实测辅助!德扑之星辅助挂多... 查到实测辅助!德扑之星辅助挂多功能透视工具,其实存在有挂(竟然有挂)一、德扑之星游戏安装教程牌型概率...
必看攻略!德扑圈辅助挂多功能透... 必看攻略!德扑圈辅助挂多功能透视工具,本来是真的有挂(有挂秘笈)1、德扑圈脚本辅助下载、德扑圈免费透...