angular angular2 form post auto submit
Problem:
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:
- avoid the form being handled by the angular framework; and (for bonus points)
- make the form dynamically auto-submit (to avoid the user having to hit a submit button)?
Solution:
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"
action="https://httpbin.org/post"
method="POST"
target="_blank" >
...
</form>
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
this.myFormPost.nativeElement.submit();
A full working example is here: angular-form-post-auto-submit (on StackBlitz)
(this includes demo handling of hidden multi-line inputs)