我有一个自定义验证器,其参数设置在上,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})]});
您应该在控制台中出现错误,因为您没有在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})]});
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句