Using Template Model Binding

One-Way Binding

If you need a form with default values, you can start using the value-binding syntax for ngModel.

app/signup-form.component.html

  1. <form #signupForm="ngForm" (ngSubmit)="register(signupForm)">
  2. <label for="username">Username</label>
  3. <input type="text" name="username" id="username" [ngModel]="generatedUser">
  4. <label for="email">Email</label>
  5. <input type="email" name="email" id="email" ngModel>
  6. <button type="submit">Sign Up</button>
  7. </form>

app/signup-form.component.ts

  1. import { Component } from '@angular/core';
  2. import { NgForm } from '@angular/forms';
  3. // ...
  4. @Component({
  5. // ...
  6. })
  7. export class SignupFormComponent {
  8. generatedUser: string = generateUniqueUserID();
  9. register(form: NgForm) {
  10. console.log(form.value);
  11. // ...
  12. }
  13. }

Two-Way Binding

While Angular assumes one-way binding by default, two-way binding is still available if you need it.

In order to have access to two-way binding in template-driven forms, use the “Banana-Box” syntax ([(ngModel)]="propertyName").

Be sure to declare all of the properties you will need on the component.

  1. <form #signupForm="ngForm" (ngSubmit)="register(signupForm)">
  2. <label for="username">Username</label>
  3. <input type="text" name="username" id="username" [(ngModel)]="username">
  4. <label for="email">Email</label>
  5. <input type="email" name="email" id="email" [(ngModel)]="email">
  6. <button type="submit">Sign Up</button>
  7. </form>
  1. import { Component } from '@angular/core';
  2. import { NgForm } from '@angular/forms';
  3. @Component({
  4. // ...
  5. })
  6. export class SignUpFormComponent {
  7. username: string = generateUniqueUserID();
  8. email = '';
  9. register(form: NgForm) {
  10. console.log(form.value.username);
  11. console.log(this.username);
  12. // ...
  13. }
  14. }

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