【问题标题】:Angular - FormBuilder.group not accepting array of validatorsAngular - FormBuilder.group 不接受验证器数组
【发布时间】:2018-11-09 00:06:00
【问题描述】:

我试图使用 Angular FormBuilder 提供的额外参数映射

group(controlsConfig: {
    [key: string]: any;
}, extra: {
    [key: string]: any;
} | null = null): FormGroup

文档:FormBuilder

但是面对

this.validator 不是函数

如果我传递单个验证器而不是数组,则上述错误消失但验证不会发生?

有人可以帮我解决这个问题或提供使用额外地图参数的正确方法吗?

我的组件及其对应的模板如下:

app.component.ts

import { Component } from '@angular/core';
import { FormControl, Validators, FormGroup, FormBuilder } from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  formGroupNew: FormGroup;
  constructor(private fb: FormBuilder) {
    this.createForm();
  }
  createForm() {
    this.formGroupNew = this.fb.group(
      { name:  "Provide name"}, 
     { validator: [Validators.required, Validators.maxLength(5)] } );
  }

  validate() {
    console.log(this.formGroupNew.controls["name"].status);
  }
}

app.component.html:

<div class="container" [formGroup]="formGroupNew">
  <input class="form-control" formControlName="name">
  <button (click)="validate()">Validate</button>
</div>

【问题讨论】:

  • name: ['', [Validators.required, Validators.minLength(2)]]

标签: angular angular-reactive-forms angular-formbuilder


【解决方案1】:

fb.group({...}, {validator: fn}) 时,第一个参数是组的控件,第二个参数是组对象本身的配置参数,而不是其中包含的控件。

该错误是因为该方法期望根据src接收一个函数而不是一个数组。

您可以在那里传递的ValidatorFn 将应用于FormGroup 对象,因此您可以创建自定义函数来检查组中多个控件的条件。出于这个原因,传递Validators.length(5) 之类的东西是没有意义的,因为组的值是一个对象(您将如何根据对象检查该条件?)。相反,Validators.required 是有意义的,因为在未设置所有控件时该值可能为 null。

假设您有两个自定义验证器函数:CustomValidatorFnOneCustomValidatorFnTwo,并且您想将它们应用于组以及所需的。你可以这样做:

fb.group({...}, {
   validator: Validators.compose(
      [
          CustomValidatorFnOne, 
          CustomValidatorFnTwo,
          Validators.required
      ]
   )
})

这样您就可以将所有验证器组合到一个函数中。

【讨论】:

    猜你喜欢
    • 2020-06-04
    • 1970-01-01
    • 1970-01-01
    • 2021-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-22
    • 2020-05-07
    相关资源
    最近更新 更多