Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't submit HTML form inside Angular 2 application

I'm trying to include static HTML form inside my Angular 2 (beta2) app but it doesn't do anything when I hit the submit button.

Here's the HTML I use:

<form action="upload_path" method="POST">   <input type="text" name="text" />   <button type="submit">Send</button> </form> 

How can I enable my form to work with Angular2?

like image 267
Roope Hakulinen Avatar asked Feb 01 '16 11:02

Roope Hakulinen


2 Answers

With

<form ngNoForm ...>  

you can prevent Angular from handling the form.

like image 166
Günter Zöchbauer Avatar answered Oct 08 '22 04:10

Günter Zöchbauer


If you want to use the action attribute of HTML form, you need to disable the behavior of the NgForm directive that catches the submit event and prevents it from being propagated. See this line: https://github.com/angular/angular/blob/master/modules/angular2/src/common/forms/directives/ng_form.ts#L81.

To do that simply add the ngNoForm attribute to your form:

<form ngNoForm action="https://www.google.com" target="_blank" method="POST">   <input name="q" value="test">   <button type="submit">Search</button> </form> 

In this case, a new window will be opened for your form submission.

That said, Angular2 tackles SPAs (Single Page Applications) and in most use cases, you need to stay in the same page when submitting a form. For such use cases, you can leverage the submit event with a submit button:

<form [ngFormModel]="companyForm" (submit)="onSubmit()">     Name: <input [ngFormControl]="companyForm.controls.name"            [(ngModel)]="company.name"/>      <button type="submit">Submit</button> </form> 

Hope it helps you, Thierry

like image 31
Thierry Templier Avatar answered Oct 08 '22 04:10

Thierry Templier