问题描述
我希望初始化表单上的某些表单字段,然后调用一个带有 if(this.form.valid)
条件的函数.
在 ngOnInit
函数上,我有一个 API 调用,它获取一些基本信息并将其填写在表单上:
ngOnInit(){this.apiService.getInfo(this.user.id).subscribe(用户信息 =>{this.formModel.fieldA = userInfo.A;this.formModel.fieldB = userInfo.B;this.formModel.fieldC = userInfo.C;this.doStuff();});}
然而,当调用 this.doStuff()
时,表单无效,即使没有错误并且点击提交按钮似乎强制验证并使其有效.
有没有一种方法可以手动触发表单的验证,以便 valid
变为 true?
所以你在 calc()
中的 if
:
if (this.formExample && this.formExample.valid)
is not truthy
并且 result
不会被计算,因为表单不是valid
.
因此,如果我们在调用 calc()
之前等待一个勾号,那应该可以解决您的问题:
this.getInfo().subscribe(信息 =>{this.params.field1 = info.field1;this.params.field2 = info.field2;//等一下!setTimeout(() => {this.calc();})});
I'm looking to initialize certain form fields on a form and then call a function that has a if(this.form.valid)
condition on it.
on the ngOnInit
function I have an API call that gets some basic info and fills it on the form:
ngOnInit(){
this.apiService.getInfo(this.user.id).subscribe(
userInfo => {
this.formModel.fieldA = userInfo.A;
this.formModel.fieldB = userInfo.B;
this.formModel.fieldC = userInfo.C;
this.doStuff();
}
);
}
However when calling this.doStuff()
the form is invalid, even though there are no errors and clicking on the submit button seems to force the validation and causes it to be valid.
Is there a way I can manually trigger the form's validation so that valid
becomes true?
Edit: Stackblitz.
Angular template-driven forms are in fact asynchronous. This is more prominently shown when working with the NgForm
directive in component, compared to reactive forms. If you were to put a debugger
in your calc()
function from the stackblitz:
You would see that in the calc
function when called from OnInit
shows that the form is not valid, nor does the form controls have any value:
So your if
in calc()
:
if (this.formExample && this.formExample.valid)
is not truthy
and result
will not be computed since the form is not valid
.
So if we wait a tick before calling calc()
that should solve your issue:
this.getInfo().subscribe(
info => {
this.params.field1 = info.field1;
this.params.field2 = info.field2;
// wait a tick!
setTimeout(() => {
this.calc();
})
}
);
这篇关于在 Angular 7 中初始化模板驱动表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!