What would be the best way to create a form onthe Fly in angular x (2 4 5) and submit it?

女生的网名这么多〃 提交于 2019-12-13 09:09:34

问题


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


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/49307817/what-would-be-the-best-way-to-create-a-form-onthe-fly-in-angular-x-2-4-5-and-s

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