角度:formArray和自定义验证器

时间:2020-06-09 13:38:08

标签: angular customvalidator formarray

我有一个嵌入formArray的主表单(可以动态添加/删除项目):

 initForm() {
    this.myMainForm = this.formBuilder.group({
      label: ['', Validators.required],
      foos: this.formBuilder.array([], fooIntegrity()),
    });
  }

<ng-container formArrayName="foos" *ngFor="let ctr of foos.controls; let i=index">
    <ngx-foo id="foo_{{ i }}" [formControlName]="i"></ngx-foo>
</ng-container>

formArray项是一个子表单:

  initForm() {
    this.fooForm = this.formBuilder.group({
    lorem: '',
    zorg: ['0', [Validators.required, Validators.min(0)]],
    bar: ['0', [Validators.required, Validators.min(0)]],
    });
  }

<div [formGroup]="fooForm">
   <div *ngIf="fooForm.errors" class="invalid-feedback d-block">
      <div *ngIf="fooForm.errors['error1']">toto</div>
      <div *ngIf="fooForm.errors['error2']">tata</div>
   </div>       
   <input type="hidden" nbInput fullWidth id="lorem" formControlName="lorem"/>  
   ...
</div>

我有一个formArray的自定义验证器:

    export function fooIntegrity(): ValidatorFn {

      return (formArray:FormArray):{[key: string]: any} | null => {

        //Return if empty
        if (!(formArray.controls.length>0)) {return;}
        ...

        for(let [i, foo] of Foos.entries()) {
            if (!foo['VALID']) {
                formArray.controls[i].setErrors({error1: true});
            }
        }
    }
}

验证器将按预期工作,并且已启用prop关联到form.valid的主表单提交按钮将相应启用/禁用。但是我无法看到子窗体错误消息。

谢谢您的帮助,

0 个答案:

没有答案