在Angular4中提交隐藏表单 [英] Submitting a hidden form in Angular4

查看:78
本文介绍了在Angular4中提交隐藏表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要解决我在提交常规HTTP请求时遇到的CORS(跨源请求共享)问题,我需要在Angular 4中提交隐藏表单.我在HTML中做到了这一点没有问题.但是,我不确定如何在Angular中做到这一点.这是我在组件的html中具有的代码:

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>

在我的.ts文件中,我实现了提交"功能.如果将其保留为空,则不会提交表单.仅在提交带有指定操作的表单后,要在此函数内编写的命令是什么?

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");
 }

有任何线索吗?

推荐答案

只要将表单附加到文档,它就可以正常工作:

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>

这将使angular忽略该表单,因此它将是纯HTML表单.该按钮将触发其提交.

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

要以编程方式提交表单,请在组件上获取表单.下面的 form 指的是上面的 #form . nativeElement 是指 HTMLFormElement .

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();
 }

然后在需要时调用 submitForm().

这篇关于在Angular4中提交隐藏表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆