I'm trying to create a contact form in Angular but I get an error in my contact-form.ts that I simply can't understand. Here is my code :
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])
})
}
}
the line that is causing me trouble is the following :
Email: new FormControl('', [Validators.compose([Validators.required, Validators.email])])
I get told
Type 'ValidatorFn | null' is not assignable to type 'ValidatorFn'.
Type 'null' is not assignable to type 'ValidatorFn'.ts(2322)
Thank you!
CodePudding user response:
Validators.compose() will return the value of ValidatorFn
or null
.
static compose(validators: null): null
You hit this error as you enable strict type checking (strict: true
) in tsconfig.json.
Would say that you don't need to use Validators.compose()
, but use an array (ValidatorFn[]
) for multiple validation checks as below:
this.FormData = this.builder.group ({
Email: new FormControl('', [Validators.required, Validators.email]),
...
})