【问题标题】:"Type 'ValidatorFn | null' is not assignable to type 'ValidatorFn'." contact-form component in angular“类型 'ValidatorFn | null' 不可分配给类型 'ValidatorFn'。”角接触形式分量
【发布时间】:2022-01-19 03:20:34
【问题描述】:

我正在尝试在 Angular 中创建一个联系表单,但我的 contact-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])])

有人告诉我

键入'ValidatorFn | null' 不能分配给类型 'ValidatorFn'。
类型 'null' 不可分配给类型 'ValidatorFn'.ts(2322)

谢谢!

【问题讨论】:

  • [Validators.compose 是否意味着在数组括号内?

标签: html angular typescript validation angular-reactive-forms


【解决方案1】:

Validators.compose() 将返回 ValidatorFnnull 的值。

静态撰写(验证器:null):null

您在 tsconfig.json 中启用严格类型检查 (strict: true) 时遇到此错误。

会说你不需要使用Validators.compose(),而是使用一个数组(ValidatorFn[]进行如下的多重验证检查:

this.FormData = this.builder.group ({
  Email: new FormControl('', [Validators.required, Validators.email]),
  ...
})

Sample Demo on StackBlitz

【讨论】:

    猜你喜欢
    • 2023-01-31
    • 2022-01-06
    • 2021-06-08
    • 2023-01-25
    • 2018-07-07
    • 1970-01-01
    • 2022-08-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多