在Angular中提交表单操作后如何触发验证并获得验证结果? [英] how to trigger validation and get validation result after submit form action in Angular?
问题描述
我有这个表单组:
this.form = this.fb.group({
id: [],
active: [true],
name: [''],
});
和此提交表单功能:
onSubmit(submitForm: FormGroup) {
this.submitForm.controls['name'].setValidators([MyValidators.unique(`name`, () => {
return this.service.checkNameUnique(this.submitForm.value.name, this.labelFg.value.id);
})]);
}
启动时我没有对表单进行验证,因为只有在我单击提交"按钮后,该表单才会被验证.因此,我使用 setValidators
函数在onSubmit函数中设置验证.
I didn't set validation to the form when initiating because this form will only be validated after I clicked the submit button. So I use the setValidators
function to set validation in onSubmit function.
但是问题是:如何触发此验证并获取验证结果?
But question is: How do I trigger this validation and get the validation result?
推荐答案
Disclamer 正如安德鲁所说,在Angular 8中,可以使用 {updateOn:'submit'}
使用formBuilder,给您带来不便
Disclamer As andrew say, from Angular 8, it's possible use {updateOn:'submit'}
using formBuilder, appologies the inconvenience
您可以使用FormGroup和Form控件的构造函数",而不是而不是formBuilder ),然后可以添加{updateOn:'submit'},请参阅文档:
You can usethe "constructors" of FormGroup and Form controls, not the formBuilder), then you can add {updateOn:'submit'}, see the docs: forms validation
this.form = new FormGroup({
id: new FormControl('',Validators.required),
active: new FormControl(true,Validators.requiredTrue),
name: new FormControl('',
{validators:Validators.required,
asyncValidators:MyValidators),
},{updateOn:'submit'});
是的,只能使用FormGroup的构造函数来做到这一点,但是您可以看到使用FormBuilder并不太不同
Yes, only can do it using the constructors of FormGroup, but you can see it's not very diferent to use FormBuilder
更新是stackblitz示例
这篇关于在Angular中提交表单操作后如何触发验证并获得验证结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!