具有参数的自定义角度验证器仅运行一次

时间:2019-04-07 03:55:49

标签: angular angular-reactive-forms

我有一个在FormGroup上设置了参数的自定义验证器,它在初始化时运行一次,但没有在任何控件更改上被触发。删除参数会在每次控件更改时运行验证器,但如果没有这些参数,显然无法使用。有什么建议让它在每个控件更改上运行?我尝试查看控件并使用updateValueAndValidity(),但仍然没有运气。

const customValidator = (options: { min: number, max: number }): ValidatorFn => {
  console.log(options);
  return (control: AbstractControl): { [key: string]: boolean } | null => {
    // logic returning null or { 'not-enough': true }
  }
}

this.form = new FormGroup({
  controlOne: new FormControl(null),
  controlTwo: new FormControl(null)
}, { validators: [customValidator({min: 5, max: 10})]});

找到解决方案

由于下面的注释和其他答案,我意识到控制台向外部登录验证器的返回功能只能运行一次。将其和其他任何附加逻辑移到return函数中,将按预期运行。最终,我的解决方案是将代码向下移动一行。

const customValidator = (options: { min: number, max: number }): ValidatorFn => {
  // No code up here will run on each control being validated
  return (control: AbstractControl): { [key: string]: boolean } | null => {
    // code down here will run on every control change
    // logic returning null or { 'not-enough': true }
  }
}

this.form = new FormGroup({
  controlOne: new FormControl(null),
  controlTwo: new FormControl(null)
}, { validators: [customValidator({min: 5, max: 10})]});

1 个答案:

答案 0 :(得分:1)

您应该在控制台中出错,因为您没有在ValidatorFn中返回任何内容:

  

src / app / app.component.ts(13,44)中的错误:错误TS2355:声明类型既不是'void'也不是'any'的函数必须返回值。

模板

  1. 确保将FormGroup绑定到表单
  2. 确保绑定每个FormControl

代码

<div style="text-align:center">
  <form [formGroup]="form">
      <input type="text" formControlName="controlOne">
      <input type="submit">
  </form>
</div>

模块

  1. 请确保导入ReactiveFormsModule

代码

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { ReactiveFormsModule } from '@angular/forms';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    ReactiveFormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

控制器

  1. 导入FormControl, FormGroup, AbstractControl, ValidatorFn
  2. ValidatorFn返回

代码

import { Component } from '@angular/core';
import { FormControl, FormGroup, AbstractControl, ValidatorFn } from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
    customValidator = (options: { min: number, max: number }): ValidatorFn => {
        return (control: AbstractControl): { [key: string]: boolean } | null => {
            console.log(options.min, options.max);
            return {};//RETURN ERRORS HERE
        }
    }

    form = new FormGroup({
        controlOne: new FormControl(null)
    }, { validators: [this.customValidator({min: 5, max: 10})]});
}
相关问题