带有参数的自定义 Angular 验证器只运行一次

Custom Angular validator with parameters only runs once

我有一个自定义验证器,其参数设置在 FormGroup 上,它在初始化时 运行ning 一次,但不会在任何控件更改时触发。删除参数 运行s 验证器在每次控制更改时,但显然没有参数就无法工作。有什么建议可以在每次控制更改时将其设置为 运行 吗?我试着观察控件并使用 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 函数。在 return 函数中移动该逻辑和任何其他附加逻辑,如预期的那样 运行s。最终我的解决方案只是将一些代码移到一行...

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})]});

您应该在控制台中遇到错误,因为您没有 return 在 ValidatorFn:

中输入任何内容

ERROR in src/app/app.component.ts(13,44): error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value.

模板

  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. return 来自 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})]});
}