我有一个在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})]});
答案 0 :(得分:1)
您应该在控制台中出错,因为您没有在ValidatorFn
中返回任何内容:
src / app / app.component.ts(13,44)中的错误:错误TS2355:声明类型既不是'void'也不是'any'的函数必须返回值。
FormGroup
绑定到表单FormControl
代码
<div style="text-align:center">
<form [formGroup]="form">
<input type="text" formControlName="controlOne">
<input type="submit">
</form>
</div>
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 { }
FormControl, FormGroup, AbstractControl, ValidatorFn
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})]});
}