"Type 'ValidatorFn | null' is not assignable to type 'ValidatorFn'." angular 中的联系表单组件
"Type 'ValidatorFn | null' is not assignable to type 'ValidatorFn'." contact-form component in angular
我正在尝试在 Angular 中创建一个联系表单,但我在我的联系人 form.ts 中收到一个我无法理解的错误。这是我的代码:
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormControl, Validators, FormGroup} from '@angular/forms';
@Component({
selector: 'app-contact-form',
templateUrl: './contact-form.component.html',
styleUrls: ['./contact-form.component.css']
})
export class ContactFormComponent implements OnInit {
FormData: FormGroup | undefined;
constructor(private builder: FormBuilder) { }
ngOnInit(): void {
this.FormData = this.builder.group ({
Fullname: new FormControl('', [Validators.required]),
Email: new FormControl('', [Validators.compose([Validators.required, Validators.email])]),
Comment: new FormControl ('', [Validators.required])
})
}
}
给我带来麻烦的行如下:
Email: new FormControl('', [Validators.compose([Validators.required, Validators.email])])
我被告知
Type 'ValidatorFn | null' is not assignable to type 'ValidatorFn'.
Type 'null' is not assignable to type 'ValidatorFn'.ts(2322)
谢谢!
Validators.compose() 将 return ValidatorFn
或 null
的值。
static compose(validators: null): null
您在 tsconfig.json 中启用严格类型检查 (strict: true
) 时遇到此错误。
会说您不需要使用 Validators.compose()
,而是使用 数组 (ValidatorFn[]
) 进行多项验证检查,如下所示:
this.FormData = this.builder.group ({
Email: new FormControl('', [Validators.required, Validators.email]),
...
})
我正在尝试在 Angular 中创建一个联系表单,但我在我的联系人 form.ts 中收到一个我无法理解的错误。这是我的代码:
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormControl, Validators, FormGroup} from '@angular/forms';
@Component({
selector: 'app-contact-form',
templateUrl: './contact-form.component.html',
styleUrls: ['./contact-form.component.css']
})
export class ContactFormComponent implements OnInit {
FormData: FormGroup | undefined;
constructor(private builder: FormBuilder) { }
ngOnInit(): void {
this.FormData = this.builder.group ({
Fullname: new FormControl('', [Validators.required]),
Email: new FormControl('', [Validators.compose([Validators.required, Validators.email])]),
Comment: new FormControl ('', [Validators.required])
})
}
}
给我带来麻烦的行如下:
Email: new FormControl('', [Validators.compose([Validators.required, Validators.email])])
我被告知
Type 'ValidatorFn | null' is not assignable to type 'ValidatorFn'.
Type 'null' is not assignable to type 'ValidatorFn'.ts(2322)
谢谢!
Validators.compose() 将 return ValidatorFn
或 null
的值。
static compose(validators: null): null
您在 tsconfig.json 中启用严格类型检查 (strict: true
) 时遇到此错误。
会说您不需要使用 Validators.compose()
,而是使用 数组 (ValidatorFn[]
) 进行多项验证检查,如下所示:
this.FormData = this.builder.group ({
Email: new FormControl('', [Validators.required, Validators.email]),
...
})