Submitting a hidden form in Angular4

落花浮王杯 提交于 2021-01-24 12:22:23

问题


To overcome a CORS (cross origin request sharing) problem I am facing with submitting a regular HTTP request, I need to submit a hidden form in Angular 4. I did that in HTML with no problem. However, I am not sure how to do that in Angular. Here is the code I have in the html of my component:

  <form form #f="ngForm" action="https://whatever.site.I_access" method="get">
   <input type="hidden" name="scope" value="openid email">
   <input type="hidden" name="response_type" value="id_token token">
   <input type="hidden" name="client_id" value="myClientId">
   <input type="hidden" name="redirect_uri" value="https://my.redirect.com/">
   <input type="hidden" name="nonce" value="aNonceValue"> 

   <button type="submit" (click)="f.submit()">Submit</button>
 </form>

In my .ts file, I have implemented the function "submit". By leaving it empty, the form is not submitted. What is the command to write inside this function just to submit the form with the specified action?

 onSubmit(){
 console.log("form submitted");
 }

Any clues?


回答1:


As long as the form is attached to the document, it should work:

  <form #form ngNoForm action="https://whatever.site.I_access" method="get">
   <input type="hidden" name="scope" value="openid email">
   <input type="hidden" name="response_type" value="id_token token">
   <input type="hidden" name="client_id" value="myClientId">
   <input type="hidden" name="redirect_uri" value="https://my.redirect.com/">
   <input type="hidden" name="nonce" value="aNonceValue"> 

   <button type="submit">Submit</button>
 </form>

This will make angular ignore the form, so it will be a plain HTML form. The button will trigger its submission.

To submit the form programatically, on the component get hold of the form. form below refers to #form above. nativeElement refers to HTMLFormElement.

 import { ..., ElementRef } from '@angular/core';
 ...
 @ViewChild('form') form: ElementRef;
 ...
 submitForm() {
   this.form.nativeElement.submit();
 }

Then call submitForm() whenever needed.



来源:https://stackoverflow.com/questions/47594827/submitting-a-hidden-form-in-angular4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!