Jesse Nelson
Jesse Nelson

Reputation: 796

Angular 6 Post form to new tab

I am trying to figure out how to set a target on a form in angular. I want the submission of the form to happen in a new tab so I have the below.

<form id="formLanding" role="form" (ngSubmit)="onSubmit()" #landingForm="ngForm" [target]="'_blank'">
...
</form>

However, angular doesn't post this to a new tab. I have read about noNgForm but this doesn't work for my use case as I already have a ton of work done that ties into Angular's form validation and this directive removes the form refernce. Does anyone know how to post a form to a new tab while still using Angular forms?

Upvotes: 1

Views: 3914

Answers (1)

Jesse Nelson
Jesse Nelson

Reputation: 796

Alright it isn't pretty but this is a requirement I can not get around. Here is how I solved.

Create another form element that will open a form in a new page with a get request (pop up blockers can not block form loads so this works)

<form  ngNoForm #htmlForm hidden action="{{window?.location?.href}}" method="get" target="_blank">
  <input name="zip" value="{{formData.zipCode}}"/>
  <input name="autoSubmit" value="true"/>
</form>

This will open the page you are currently on in a new tab with the form values as query params. Then in your component you can get a reference to the form

@ViewChild("htmlForm")
htmlForm: ElementRef;

and in your click handler for the angular managed form you can do what ever logic you need plus

this.htmlForm.nativeElement.submit();

Then on the init of the component you can read these form values and automatically submit.

ngOnInit() {
    this.activatedRoute.queryParams.subscribe(params => {
      if (params && params.autoSubmit) {

        this.formData.zipCode = params.zip;
        //submit this.formData to the server. 
      }
    });
  }

Upvotes: 3

Related Questions