我正在自定义我的表单并创建自己的验证器。但我做错了,因为它总是崩溃:
**my-component.ts**
export function ageRangeValidator(min: number, max: number): ValidatorFn {
return (control: AbstractControl): { [key: string]: boolean } | null => {
if (control.value !== undefined && (isNaN(control.value) || control.value < min || control.value > max)) {
return { 'ageRange': true };
}
return null;
};
}
@Component({
selector: 'my-component',
templateUrl: './my-component.html',
styleUrls: ['./my-component.scss']
})
export class MyComponent implements OnInit {
form: FormGroup;
constructor(private fb: FormBuilder) {
}
ngOnInit() {
this.form = this.fb.group({
name: ['', [Validators.required],
age: ['', [Validators.required, ageRangeValidator(20, 30)]]
}
}
创建表单时,我崩溃了
Error: formGroup expects a FormGroup instance. Please pass one in.
Example:
<div [formGroup]="myGroup">
<input formControlName="firstName">
</div>
In your class:
this.myGroup = new FormGroup({
fistName: new FormControl()
});
如果我删除表单定义中的验证器,它就可以工作。
我在做什么错?