如何在Angular2中将表单提交到服务器? [英] How to submit form to server in Angular2?

查看:67
本文介绍了如何在Angular2中将表单提交到服务器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在,即使在< form>中使用action =,提交也已被angular2捕获.

Now the submission has been caught by angular2 even with action= in the <form>.

演示链接: http://plnkr.co/edit/4wpTwNw1iCPeublhNumT5?p=preview

//our root app component
import {Component} from 'angular2/core'

@Component({
  selector: 'my-app',
  providers: [],
  template: `
    <div>
      <h2>Hello {{name}}</h2>
      <form action="https://www.google.com" target="_blank" method="POST">
        <input name="q" value="test">
        <button type="submit">Search</button>
      </form>
    </div>
  `,
  directives: []
})
export class App {
  constructor() {
    this.name = 'Angular2'
  }
}

推荐答案

您应该利用NgSubmit指令,如下所述:

You should leverage the NgSubmit directive, as described below:

<form (ngSubmit)="onSubmit()" #heroForm="ngForm">
  (...)
  <input type="text" [(ngModel)]="data.name"/>
  (...)
  <button type="submit">Send</button>
</form>

在这种情况下,当您单击提交"按钮时,将调用组件的onSubmit方法,您将能够使用Angular2上的HTTP类将数据手动发送到服务器:

In this case, when you click on the submit button, the onSubmit method of the component will be called and you'll be able to manually send data to the server using the HTTP class on Angular2:

@Component({
})
export class MyComponent {
  constructor(private http:Http) {
    this.data = {
      name: 'some name'
      (...)
    };
  }

  onSubmit() {
    this.http.post('http://someurl', JSON.stringify(this.data))
        .subscribe(...);
  }
}

这样,您可以保留在同一页面上.

This way you can remain in the same page page.

修改

在注释之后,您需要禁用NgForm指令的行为,该指令会捕获submit事件并阻止其传播.看到以下行: https://github.com/angular/angular/blob/master/modules/%40angular/forms/src/directives/ng_form.ts#L141 .

Following your comment, 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/%40angular/forms/src/directives/ng_form.ts#L141.

为此,只需将ngNoForm属性添加到您的表单中即可:

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.

希望它对您有帮助, 蒂埃里

Hope it helps you, Thierry

这篇关于如何在Angular2中将表单提交到服务器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆