Template-Driven Forms

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

First, consider a typical form:

  1. <form method="POST" action="/register" id="signup-form">
  2. <label for="email">Email</label>
  3. <input type="text" name="email" id="email">
  4. <label for="password">Password</label>
  5. <input type="password" name="password" id="password">
  6. <button type="submit">Sign Up</button>
  7. </form>

Angular 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

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

signup-form.component.html

  1. <form #signupForm="ngForm" (ngSubmit)="registerUser(signupForm)">
  2. <label for="email">Email</label>
  3. <input type="text" name="email" id="email" ngModel>
  4. <label for="password">Password</label>
  5. <input type="password" name="password" id="password" ngModel>
  6. <button type="submit">Sign Up</button>
  7. </form>

signup-form.component.ts

  1. import { Component } from '@angular/core';
  2. import { NgForm } from '@angular/forms';
  3. @Component({
  4. selector: 'app-signup-form',
  5. templateUrl: 'app/signup-form.component.html',
  6. })
  7. export class SignupFormComponent {
  8. registerUser(form: NgForm) {
  9. console.log(form.value);
  10. // {email: '...', password: '...'}
  11. // ...
  12. }
  13. }

原文: https://angular-2-training-book.rangle.io/handout/forms/template-driven/template-driven_forms.html