jimbo2087
jimbo2087

Reputation: 1054

Submitting a form to an Angular 2 App

What is the best way to submit a form to an Angular 2 app? I.e. from a non-angular website, to an Angular app?

You cannot simply put the app as the action URL with method="GET" as Angular 2 uses "matrix URL notation" and the browser will add the form fields as regular params (?= , &=).

For example this approach does not work, assuming the URL is an Angular 2 app:

<form method="GET" action="http://myangular2app.com/search;">
    <input name="q">
    <input type="submit" value="Go">
</form>

The browser will navigate to a URL like http://myangular2app.com/search;?q=mysearch when it needs to be http://myangular2app.com/search;q=mysearch (no question mark).

Upvotes: 1

Views: 181

Answers (1)

Christopher Moore
Christopher Moore

Reputation: 3099

You can utilise two-way binding with use of the ngModel directive

<input name="q" [(ngModel)]='name'>

You will need to import the forms modules to utilise two-way binding; as well as the Http module for the request:

import { FormsModule } from '@angular/forms';
import { Http }        from '@angular/http';

Use this for the call:

this.http.get("http://myangular2app.com/search;q="+mysearch)

If you are new to Angular2 I would recommend you spend a bit of time looking of the Angular2 tutorial 'Tour of Heroes'

This walks you through creating a simple web application involving (among other things) forms, data binding and HTTP requests

Upvotes: 1

Related Questions