I have an angular x(2 4 5) app, and i must make a post redirect to a bank page, so the user can pay something.
So, I want to create a form on the fly in my DOM and post it. Can't find the best way. It's easy to loop and create a form, but not easy to directly post it after drawing it.
thanks in advance
As @DeborahK mentioned, you probably can't directly post an Angular form.
However, there's no reason that you can't get the data from the form, and pass it to a service that uses the HttpClient library to do an HTTP POST with a content-type of multipart/form-data.
Something like this:
const headers = new HttpHeaders({'Content-Type': 'multipart/form-data'});
const formData = new FormData();
formData.append("name","username");
// repeat formData.append for additional form fields
this.httpClient.post<any>(URL, formData, {headers: headers});
You can use a form with the fields hidden and ViewChild to get the reference of the form, e.g.
@Component({
selector: 'my-app',
template: `
<button (click)="sendData()">send</button>
<form #externalForm method="post" action="http://url-comerce" target="_blank">
<input type="hidden" id="data1" name="data1" [ngModel]="comerceData.data1">
<input type="hidden" id="data2" name="data2" [ngModel]="comerceData.data2" >
</form>
`,
})
export class HomeComponent {
comerceData:any={}
@ViewChild('externalForm') externalForm: ElementRef;
constructor() { }
sendData() {
//fill the data to send
this.comerceData={
data1:"something",
data2:"something more"
}
//Use a setTimeout. if not, the change of the data are not send
setTimeout(()=>{
this.externalForm.nativeElement.submit()
}, 0);
}
}