反应性表单数组-推送新元素时避免验证错误 [英] Reactive Form Array - Avoid Validation Error when push new elements

查看:85
本文介绍了反应性表单数组-推送新元素时避免验证错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个由单个表单数组组成的表单组:

I have a form group which is composed by a single form array:

    ngOnInit() {
        this.deviceDetailsFormGroup = this._formBuilder.group({
            deviceDetails: this._formBuilder.array([
                this.buildDeviceDetailsForm()
            ])
        });
}

表单数组中的每个控件都具有必需的验证器:

Each control in the Form Array has required validators:

buildDeviceDetailsForm(): FormGroup {
    return this._formBuilder.group({
        ipAddressCtrl: [
            "",
            [Validators.pattern(ipaddressPattern), Validators.required]
        ],
        hostnameCtrl: [
            "",
            [
                Validators.required,
                Validators.maxLength(30),
                Validators.minLength(5)
            ]
        ]
    });
}

下面是我对表单数组的推入和删除功能:

Below are my push and remove functions to the Form Array:

addNewDevice() {
    this.deviceItems = this.deviceDetailsFormGroup.get(
        "deviceDetails"
    ) as FormArray;

    if (this.deviceItems.length > MAX_DEVICES) {
        this.toastNotif.errorToastNotif(
            `A maximum of ${MAX_DEVICES} devices can be selected for a single job scan`,
            "Too many devices selected"
        );
        return;
    }

    if (this.deviceDetailsFormGroup.invalid) {
        return;
    }

    let mapIP = new Map<string, number>();

    // Warn about duplicate IP's in form
    this.deviceItems.controls.forEach(ctrl => {
        if (mapIP[ctrl.value.ipAddressCtrl] === 0) {
            this.toastNotif.warningToastNotif(
                "You have entered duplicate IP's in the form fields",
                "Duplicate" + " IP's"
            );
        }

        mapIP[ctrl.value.ipAddressCtrl] = 0;
    });

    this.deviceItems.push(this.buildDeviceDetailsForm());
}

removeDevice(i: number) {
    this.deviceItems.removeAt(this.deviceItems.length - 1);
}

当我将新元素推送到表单数组"时,它们会被标记为无效,尽管它们未被修饰且原始.我了解这是由创建新FormGroup时验证程序和设置为空的默认值引起的.

When I push new elements to the Form Array, they're marked as invalid although they're untouched and pristine. I understand that's caused by the Validators and empty default values set when I create the new FormGroup.

是否有可能避免这种行为,因此仅在触摸FormArray元素时才将它们标记为错误?

Is it possible to avoid this behaviour so the FormArray elements are marked as errors only if they're touched ?

谢谢.

推荐答案

Luca,FormArray中的formControl始终是无效的,因此FormArray无效且表单无效.您需要检查控件是否被触摸. 此stackblitz 中的一个简单示例.您会看到,如果添加该控件,则该控件无效,但未被触摸

Luca, the formControl in the FormArray will be invalid always, so the FormArray is invalid and the form is invalid. You need check if the control is touched. A simple example in this stackblitz. You see that if you add, the control is invalid, but not touched

.html是一种典型形式

The .html is a tipical form

<button (click)="add()">Add</button>
<form [formGroup]="myForm">
<div formArrayName="myFormArray">
  <div *ngFor="let group of myFormArray.controls;let i=index" [formGroupName]="i">
       <input formControlName="name">
       <!--show only after touched and invalid-->
       <div *ngIf="group.get('name').touched && group.get('name').invalid">
         invalid and touched
       </div>
       <!--show always when add a new formGroup to array-->
       <div *ngIf="group.get('name').invalid">
         invalid 
       </div>
  </div>
  </div>
  </form>

.ts是经典"

myForm=new FormGroup({
     myFormArray:new FormArray([])
  })

  get myFormArray()
  {
    return this.myForm.get('myFormArray') as FormArray
  }
  createGroup()
  {
    return new FormGroup({
      name:new FormControl('',Validators.required)
    })
  }
  add()
  {
    this.myFormArray.push(this.createGroup())
  }

这篇关于反应性表单数组-推送新元素时避免验证错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆