问题
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