简体   繁体   English

Angular - 可以在没有初始值的情况下在 FormControl 上使用验证器吗?

[英]Angular - Can you use a Validator on a FormControl without an initial value?

I have a FormControl without an initial value but I would like to add Validators.required to it.我有一个没有初始值的FormControl ,但我想向它添加Validators.required The initial value is the first argument, Do I have to give it an initial value?初始值是第一个参数,我必须给它一个初始值吗? (empty string, false, etc) (空字符串、假等)

this.contactForm = new FormGroup({
    name: new FormControl('', Validators.required),
    email: new FormControl('', [Validators.required, CustomEmailValidator]),
    optInEmails: new FormControl(false, Validators.required)
})

The constructor for the Form Control in Angular is as follows: Angular中Form Control的构造函数如下:

constructor(formState: any = null, validatorOrOpts?: ValidatorFn | AbstractControlOptions | ValidatorFn[], asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[])

The formState attribute sets the initial value to the FormControl Object you create. formState 属性将初始值设置为您创建的 FormControl Object。

The values for the attributes need to be specified in the same order as the constructor.需要以与构造函数相同的顺序指定属性的值。 Hence, you can define your formControl as optInEmails: new FormControl(null, Validators.required)因此,您可以将 formControl 定义为optInEmails: new FormControl(null, Validators.required)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM