问题
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.
回答1:
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();
})
}
);
STACKBLITZ
来源:https://stackoverflow.com/questions/58018506/initializing-template-driven-form-in-angular-7