Home > Mobile >  Submit form as POST request and open new tab/window in Angular
Submit form as POST request and open new tab/window in Angular

Time:04-24

I'm using Angular and I want to submit a form as POST request and open the result in a new window or tab. I need to send the an authentication token either in Authorization header or in the POST body, not as GET query parameter. It's a project requirement to not use AJAX for this request.

I've tried a form in the index.html outside the Angular root component:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>Angular</title>
    <base href="/" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link rel="icon" type="image/x-icon" href="favicon.ico" />
    <link rel="preconnect" href="https://fonts.gstatic.com" />
    <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500&display=swap" rel="stylesheet" />
    <link href="https://fonts.googleapis.com/icon?family=Material Icons" rel="stylesheet" />
  </head>

  <body >
    <form method="post" target="_blank" action="https://www.google.com/">
      <input type="hidden" value="auth-token">
      <button mat-button color="primary" type="submit">
        Submit
      </button>
      <input type="submit" value="Submit" />
    </form>
    <app-root></app-root>
  </body>
</html>

This works as expected. The form is sent and the result is shown in a new tab. But I need this functionality inside a ngFor inside a mat-table.

When I move this form into the root Angular component

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
    <form method="post" target="_blank" action="https://www.google.com/">
      <input type="hidden" value="auth-token">
      <button mat-button color="primary" type="submit">
        Submit
      </button>
      <input type="submit" value="Submit" />
    </form>`,
  styleUrls: ['./app.component.scss']
})
export class AppComponent {}

I can see the form and the buttons, but a click neither sends the form nor opens a new tab.

I've imported FormsModule and use/need the module in the project. I guess, the module blocks the default behavior of the form. Is it possible to force the default behavior of a form submit inside an Angular project that imports FormsModule?

I've checked https://angular.io/api/forms/NgForm but can't find an option to allow the default behavior. I also tried to import ReactiveFormsModule.

This Stackblitz demonstrates the problem. The upper two buttons are outside the Angular component and open a new tab/window. The lower two buttons are inside the Angular component and don't do anything.

Since someone voted to close because of missing debugging details, here are the files from Stackblitz:

index.html:

<form method="post" target="_blank" action="https://www.google.com/">
  <input type="hidden" value="auth-token" />
  <button mat-button color="primary" type="submit">Submit</button>
  <input type="submit" value="Submit" />
</form>
<my-app>loading</my-app>

app.module.ts:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';

import { AppComponent } from './app.component';

@NgModule({
  imports:      [ BrowserModule, FormsModule ],
  declarations: [ AppComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

app.component.ts:

import { Component, VERSION } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html'
})
export class AppComponent  {
  name = 'Angular '   VERSION.major;
}

app.component.ts:

<form method="post" target="_blank" action="https://www.google.com/">
  <input type="hidden" value="auth-token" />
  <button mat-button color="primary" type="submit">Submit</button>
  <input type="submit" value="Submit" />
</form>

main.ts:

import './polyfills';

import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

import { AppModule } from './app/app.module';

platformBrowserDynamic().bootstrapModule(AppModule).then(ref => {
  // Ensure Angular destroys itself on hot reloads.
  if (window['ngRef']) {
    window['ngRef'].destroy();
  }
  window['ngRef'] = ref;

  // Otherwise, log the boot error
}).catch(err => console.error(err));

polyfill.ts:

import 'zone.js/dist/zone';

angular.json:

{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "demo": {
      "root": "",
      "sourceRoot": "src",
      "projectType": "application",
      "prefix": "app",
      "schematics": {},
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist/demo",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "src/tsconfig.app.json",
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
            ],
            "scripts": []
          },
          "configurations": {
            "production": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ],
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "extractCss": true,
              "namedChunks": false,
              "aot": true,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true
            }
          }
        },
        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "demo:build"
          },
          "configurations": {
            "production": {
              "browserTarget": "demo:build:production"
            }
          }
        },
        "extract-i18n": {
          "builder": "@angular-devkit/build-angular:extract-i18n",
          "options": {
            "browserTarget": "demo:build"
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "src/test.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "src/tsconfig.spec.json",
            "karmaConfig": "src/karma.conf.js",
            "styles": [
              "styles.css"
            ],
            "scripts": [],
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ]
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": [
              "src/tsconfig.app.json",
              "src/tsconfig.spec.json"
            ],
            "exclude": [
              "**/node_modules/**"
            ]
          }
        }
      }
    }
  },
  "defaultProject": "demo"
}

package.json:

{
  "name": "angular",
  "version": "0.0.0",
  "private": true,
  "dependencies": {
    "@angular/animations": "^13.2.0",
    "@angular/common": "^13.2.0",
    "@angular/compiler": "^13.2.0",
    "@angular/core": "^13.2.0",
    "@angular/forms": "^13.2.0",
    "@angular/platform-browser": "^13.2.0",
    "@angular/platform-browser-dynamic": "^13.2.0",
    "@angular/router": "^13.2.0",
    "rxjs": "^7.5.2",
    "tslib": "^2.3.1",
    "zone.js": "^0.11.4"
  },
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~0.1100.4",
    "@angular/cli": "~11.0.4",
    "@angular/compiler-cli": "~11.0.4",
    "@types/jasmine": "~3.6.0",
    "@types/node": "^12.11.1",
    "codelyzer": "^6.0.0",
    "jasmine-core": "~3.6.0",
    "jasmine-spec-reporter": "~5.0.0",
    "karma": "~5.1.0",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage": "~2.0.3",
    "karma-jasmine": "~4.0.0",
    "karma-jasmine-html-reporter": "^1.5.0",
    "protractor": "~7.0.0",
    "ts-node": "~8.3.0",
    "tslint": "~6.1.0",
    "typescript": "~4.0.2"
  }
}

tsconfig.json:

{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "downlevelIteration": true,
    "experimentalDecorators": true,
    "module": "esnext",
    "moduleResolution": "node",
    "importHelpers": true,
    "target": "es2015",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2018",
      "dom"
    ]
  },
  "angularCompilerOptions": {
    "enableIvy": true,
    "fullTemplateTypeCheck": true,
    "strictInjectionParameters": true
  }
}

CodePudding user response:

Import the ReactiveFormsModule in your App.module.ts file

Update:

try it this way:

<form #form method="post" target="_blank" action="https://www.google.com/">
  <input type="hidden" value="auth-token" />
  <button mat-button color="primary" type="submit" (click)="form.submit()">Submit</button>
  <input type="submit" value="Submit" />
</form>

CodePudding user response:

angular form modules intercept the form element submit event. You can bind to ngSubmit and submit the form with the element reference, either submit method / button will work in this approach:

<form
  #authForm
  method="post"
  target="_blank"
  action="https://www.google.com/"
  (ngSubmit)="authForm.submit()"
>
  <input type="hidden" value="auth-token" />
  <button mat-button color="primary" type="submit">Submit</button>
  <input type="submit" value="Submit" />
</form>
  • Related