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

相关内容

热门资讯

玩家必备科普“德州hhpoke... 玩家必备科普“德州hhpoker脚本”开挂(透视)辅助安装(技巧教程有挂分享);打开点击测试直接进入...
开挂辅助工具"约局吧... 开挂辅助工具"约局吧能不能开挂"开挂(透视)辅助平台(有挂透视)您好:约局吧能不能开挂这款游戏可以开...
辅助开挂!山西扣点子技巧,aa... 辅助开挂!山西扣点子技巧,aapoker免费透视脚本(透视)开挂辅助插件(竟然有挂);1、让任何用户...
重大通报“wepoker怎么设... 开挂教程视频分享装挂详细步骤在当今的网络游戏中,作为一种经典的娱乐方式,吸引了无数玩家的参与。尤其是...
开挂辅助软件"wep... 开挂辅助软件"wepoker辅助器怎么弄"开挂(透视)辅助脚本(果真有挂);无需打开直接搜索加薇13...
开挂辅助!广东雀神智能辅助照片... 开挂辅助!广东雀神智能辅助照片,wepoker怎么提高运气(透视)开挂辅助插件(真的有挂);广东雀神...
六分钟了解“wepoker免费... 六分钟了解“wepoker免费辅助器”开挂(透视)辅助插件(必备教程有挂细节)>>您好:软件加薇13...
开挂辅助插件"wep... 开挂辅助插件"wepoker透视最简单三个步骤"开挂(透视)辅助工具(有挂教学)您好:wepoker...
辅助开挂!崇阳斗棋辅助脚本视频... 辅助开挂!崇阳斗棋辅助脚本视频,聚星ai辅助工具收费多少(透视)开挂辅助下载(有挂教程);人气非常高...
科普分享“wpk辅助是什么”开... 科普分享“wpk辅助是什么”开挂(透视)辅助脚本(AI教程有挂方略) 了解更多开挂安装加(13670...