Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

"Type 'ValidatorFn | null' is not assignable to type 'ValidatorFn'." contact-form component in angular

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Type ‘ValidatorFn | null’ is not assignable to type ‘ValidatorFn’.
Type ‘null’ is not assignable to type ‘ValidatorFn’.ts(2322)

Thank you!

>Solution :

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]),
  ...
})

Sample Demo on StackBlitz

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading