简体   繁体   中英

Angular 7 - ngForm, ngSubmit - submitting old values

I am using form in Angular 7 as below

<form #payForm="ngForm" (ngSubmit)="onSubmit(payForm, $event)" method="POST" action="POST URL HERE">
      <input type="hidden" name="requestParameter" [value]="stringToSend" />
      <div class="text-center">
        <input type="submit" class="btn blbtn text-uppercase px-5 py-2 rounded my-3" value="Pay Now">
      </div>
      <div class="text-center">
        <a [routerLink]="['/logout']" class="onerem ltbl-link w-auto d-inline-block">Cancel</a>
      </div>
</form>

Here "stringToSend" is getting calculated each time there is some user action like different plan selection or coupon selection. But when he finally clicks on "Pay Now" button, then I want to submit form to the POST URL from my angular component, so I am calling using ngForm with (ngSubmit)="onSubmit(payForm, $event)"

Below is my code from controller

onSubmit(form: any, clkEvent: any): void {

// some database inserts before form submit
stringToSend = newCalculatedValue;   // setting stringToSend to new calculated value

clkEvent.target.submit();   // actual form submit from controller

}

But when I submit this form, the last value of stringToSend is getting send with form as form data not the latest one which I am calculating inside onSubmit() function.

Before setting latest value I consoled it, it's showing fine, but with form last value is submitting which is my Problem in angular. I also tried [(ngModel)] but still no luck.

Any help is appreciated.

Thanks, Rohit

The reason for not picking up latest value is how angular bindings work. The input element is binded to stringToSend variable, but before angular gets a chance to update the bindings to the actual DOM node, the form gets submitted. One way to fix this issue, is to delay the form posting in the next event loop cycle (eg. using a setTimeout ).

onSubmit(form: any, clkEvent: any): void {

    // some database inserts before form submit
    stringToSend = newCalculatedValue;   // setting stringToSend to new calculated value
    setTimeout(()=>{
       clkEvent.target.submit();   // actual form submit from controller
    } , 0);
}

However, the above solution would a hacky way to fix the issue. Ideally, form submission should be delegated to a service.

Refer to the docs for some best practices when dealing with form controls.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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