我有一个自定义验证器,其参数设置在 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})]});
找到解决方案感谢下面的评论和其他答案,我意识到我的控制台在外部登录验证器的返回功能只运行一次。在返回函数内移动该逻辑和任何其他附加逻辑,按预期运行。最终我的解决方案只是将一些代码向下移动......
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})]});
最佳答案
您应该在控制台中出现错误,因为您的 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.
模板
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 { }
Controller
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})]});
}
关于angular - 带有参数的自定义 Angular 验证器只运行一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55555480/