Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular-FormBuilder.group不接受验证程序数组_Angular_Angular Reactive Forms_Angular Formbuilder - Fatal编程技术网

Angular-FormBuilder.group不接受验证程序数组

Angular-FormBuilder.group不接受验证程序数组,angular,angular-reactive-forms,angular-formbuilder,Angular,Angular Reactive Forms,Angular Formbuilder,我试图使用Angular FormBuilder提供的额外参数映射 group(controlsConfig: { [key: string]: any; }, extra: { [key: string]: any; } | null = null): FormGroup 文件: 但是面对 this.validator不是一个函数 如果我传递的是单个验证器而不是数组,那么上面的错误会消失,但验证不会发生 有人能帮我吗?或者提供使用额外map参数的正确方法吗 我的组件及其对应的

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

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

但是面对

this.validator不是一个函数

如果我传递的是单个验证器而不是数组,那么上面的错误会消失,但验证不会发生

有人能帮我吗?或者提供使用额外map参数的正确方法吗

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

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>

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

导致此错误的原因是,该方法希望接收函数,而不是根据

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

假设您有两个自定义验证器函数:
CustomValidatorFnOne
CustomValidatorFnTwo
,您希望将它们应用于组和所需的。你可以这样做:

fb.group({...}, {
   validator: Validators.compose(
      [
          CustomValidatorFnOne, 
          CustomValidatorFnTwo,
          Validators.required
      ]
   )
})
这样,您就可以将所有验证器组成一个函数。

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