Template-Driven Forms

The most straightforward approach to building forms in Angular 2 is to take advantage of the directives provided for you.

First, consider a typical form:

<form method="POST" action="/register" id="SignupForm">
  <label for="email">Email</label>
  <input type="text" name="email" id="email">

  <label for="password">Password</label>
  <input type="password" name="password" id="password">

  <button type="submit">Sign Up</button>
</form>

Angular 2 has already provided you a form directive, and form related directives such as input, etc which operates under the covers. For a basic implementation, we just have to add a few attributes and make sure our component knows what to do with the data.

index.html

<signup-form>Loading...</signup-form>

signup-form.component.html

<form #signupForm="ngForm" (ngSubmit)="registerUser(signupForm)">
  <label for="email">Email</label>
  <input type="text" name="email" id="email" ngModel>

  <label for="password">Password</label>
  <input type="password" name="password" id="password" ngModel>

  <button type="submit">Sign Up</button>
</form>

signup-form.component.ts

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

@Component({
  selector: 'signup-form',
  templateUrl: 'app/signup-form.component.html',
  providers: [NgForm]
})
export class SignupForm {
  registerUser (form: NgForm) {
    console.log(form.value);
    // {email: '...', password: '...'}
    // ...
  }
}

results matching ""

    No results matching ""