Angular form学习笔记
https://angular.io/start/start-forms
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創(chuàng)建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屬性構(gòu)造一個(gè)包含了兩個(gè)字段的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標(biāo)簽。
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:是一個(gè)directive,將FormGroup里一個(gè)FormControl模型sync到template里的form control element里去。
更多Jerry的原創(chuàng)文章,盡在:“汪子熙”:
總結(jié)
以上是生活随笔為你收集整理的Angular form学习笔记的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 泥鱼龙在哪
- 下一篇: 使用Visual Studio Code