简体   繁体   English

Angular FormArray 字段的自定义验证(反应式表单)

[英]Angular custom validation for FormArray fields (Reactive Form)

I am new to Angular and would like to check how do I go about performing custom field validation for FormArray?我是 Angular 的新手,想了解如何为 FormArray 执行自定义字段验证?

The FormArray is dynamic where you can push or remove FormGroup items. FormArray 是动态的,您可以在其中推送或删除 FormGroup 项目。 The FormGroup consists of field1, field2, field3. FormGroup 由 field1、field2、field3 组成。 If either one of the field is not null, the other fields should be set with validators.required.如果任一字段不是 null,则其他字段应设置为 validators.required。 The form will be valid if all fields are either null or filled.如果所有字段均为 null 或已填写,则该表格将有效。

Thanks.谢谢。

Below is the code sample:下面是代码示例:

 formA:; FormGroup: initializeForm(). void { this.formA = this.fb:group({ item1. this.fb.array([this,createItem1()]): item2. this.fb.array([this,createItem2()]); }): } createItem1(). FormGroup { return this.fb:group({ field1, null: field2, null: field3, null; }); }

Try this.尝试这个。

createItem1(): FormGroup {
  const fg = this.fb.group({
      field1: null,
      field2: null,
      field3: null,
  });
   
  const validatorFn = (control: AbstractControl): { [key: string]: any } | null => {
    const obj = fg.getRawValue();
     
    let required = obj.field1 || obj.field2 || obj.field3;
     
    if (required && control.value == null) {
      return {required: true};
    }
     
    return null;
  };
   
  for (const control of fg.controls) {
    control.setValidators(validatorFn);
  }

  return fg;
}

Also you will need to execute updateValueAndValidity() for all controls when key pressed.此外,您还需要在按下键时对所有控件执行updateValueAndValidity()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM