使用 Model 绑定

单向绑定

如果您需要具有默认值的表单,可以开始使用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. export class SignupForm {
  6. generatedUser: string = generateUniqueUserID();
  7. register(form: NgForm) {
  8. console.log(form.value);
  9. // ...
  10. }
  11. }

双向绑定

虽然Angular 2默认情况下假定单向绑定,但如果需要,双向绑定仍然可用。
为了能够访问模板驱动表单中的双向绑定,请使用“Banana-Box”语法([(ngModel)] ="propertyName")。请务必声明组件上需要的所有属性。

  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. // ...
  4. @Component({ /* ... */ })
  5. export class SignUpForm {
  6. username: string = generateUniqueUserID();
  7. email: string = '';
  8. register(form: NgForm) {
  9. console.log(form.value.username);
  10. console.log(this.username);
  11. // ...
  12. }
  13. }