1

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.

5
  • this.form.updateValueAndValidity() Commented Sep 19, 2019 at 20:47
  • @joyBlanks I'm getting a "Property 'updateValueAndValidity' does not exist on type 'NgForm'". Commented Sep 19, 2019 at 21:25
  • can you put up a small stackblitz with some dummy data use of({}).subscribe to simulate the apiservice Commented Sep 19, 2019 at 21:34
  • how does your template look like? Commented Sep 20, 2019 at 10:53
  • I've added a Stackblitzwith dummy data. Commented Sep 20, 2019 at 14:38

1 Answer 1

3

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:

enter image description here

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.