How to submit form to server in Angular2?

前端 未结 4 1520
萌比男神i
萌比男神i 2020-12-01 03:47

Now the submission has been caught by angular2 even with action= in the

.

demo link: http://plnkr.co/edit/4wpTwN0iCPeublhNumT5?p=preview



        
相关标签:
4条回答
  • 2020-12-01 03:59

    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>
    

    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.

    Edit

    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.

    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

    0 讨论(0)
  • 2020-12-01 04:04

    You can also submit form in this way.

    Here is HTML markup.

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

    And here is code in your .ts file.

    onSubmit(e) {
        e.target.submit();
      }
    
    0 讨论(0)
  • 2020-12-01 04:04

    Hey if any one else ever has some annoying issue in Firefox when posting a form to a new url causes a page refresh and does not follow through to the page add target="_parent" and will fix the issue.

    0 讨论(0)
  • 2020-12-01 04:24

    Try this:

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

    http://plnkr.co/edit/Qjh8ooPpkfVgEe0dIv4q?p=preview

    0 讨论(0)
提交回复
热议问题