Wednesday, July 11, 2018

Perform an Auto-Submit Form Post from an Angular page

angular angular2 form post auto submit

You need to send the user to another application (in the current view or new window) via a form-post that includes a payload of inputs.

How do you:
  1. avoid the form being handled by the angular framework; and (for bonus points)
  2. make the form dynamically auto-submit (to avoid the user having to hit a submit button)?

For (a) the key to ensuring the form element in the template is not handled by the angular framework - and therefore allowing it to submit to the defined action is adding the ngNoForm attribute. There's notes in a discussion How to submit form to server in Angular2 ... at the time of writing, it doesn't appear to be well documented.

<form ngNoForm 
    #myFormPost name="myFormPost" 
    target="_blank" >

For (b) the dynamic auto-submit, you can obtain the reference to the form and submit it from the component code:
@ViewChild('myFormPost') myFormPost: ElementRef;
  // in some place where the form has been set

A full working example is here: angular-form-post-auto-submit (on StackBlitz)
(this includes demo handling of hidden multi-line inputs)