Angular form学习笔记

187 阅读1分钟

angular.io/start/start…

Angular里的form分成两部分:

the objects that live in the component to store and manage the form, and the visualization of the form that lives in the template.

  • 位于Component里的objects, 用于store和管理form
  • 以及template里的visualization部分。

the form model is the source of truth for the status of the form.

Angular’s FormBuilder service provides convenient methods for generating controls.

使用Angular的FormBuilder创建controls.

import { FormBuilder } from '@angular/forms';

The ReactiveFormsModule provides the FormBuilder service, which AppModule (in app.module.ts) already imports.

define the checkoutForm property to store the form model.

export class CartComponent implements OnInit {
  items;
  checkoutForm;
}

使用FormBuilder提供的group方法给checkoutForm属性构造一个包含了两个字段的form模型:name和address

export class CartComponent implements OnInit {
  items;
  checkoutForm;

  constructor(
    private cartService: CartService,
    private formBuilder: FormBuilder,
  ) {
    this.checkoutForm = this.formBuilder.group({
      name: '',
      address: ''
    });
  }

  ngOnInit() {
    this.items = this.cartService.getItems();
  }
}

在Component里完成checkoutForm的模型定义之后,还需要在Angular Component template里完成visualization部分:

<form [formGroup]="checkoutForm">

  <button class="button" type="submit">Purchase</button>

</form>

使用formGroup将Component的checkoutForm属性绑定到form标签。

Use the formControlName attribute binding to bind the checkoutForm form controls for name and address to their input fields.
使用formControlName将checkoutForm模型里的name和address字段绑定到input fields上。

formControlName:是一个directive,将FormGroup里一个FormControl模型sync到template里的form control element里去。

更多Jerry的原创文章,尽在:“汪子熙”: