1、cart.component.html
姓名、地址和提交组成的表单
checkoutForm 属性来存储表单模型
// ngSubmit 事件绑定来监听表单提交,并使用 checkoutForm 值调用 onSubmit() 方法<form [formGroup]=\"checkoutForm\" (ngSubmit)=\"onSubmit(checkoutForm.value)\"><div><label for=\"name\">Name</label><input id=\"name\" type=\"text\" formControlName=\"name\"></div><div><label for=\"adress\">Address</label><input id=\"address\" type=\"text\" formControlName=\"address\"></div><button class=\"button\" type=\"submit\" >Purchase</button></form>
2、app.module.ts
import { FormsModule,ReactiveFormsModule } from \'@angular/forms\';imports: [FormsModule,ReactiveFormsModule,],
否则,报错:Can’t bind to ‘formGroup’ since it isn’t a known property of ‘form’.
3、cart.component.ts
import { Component, OnInit } from \'@angular/core\';import { CartService } from \'../cart.service\';import { FormBuilder } from \'@angular/forms\';@Component({selector: \'app-cart\',templateUrl: \'./cart.component.html\',styleUrls: [\'./cart.component.css\']})export class CartComponent implements OnInit {items;checkoutForm;// checkoutForm 包含 name 和 address 字段的表单模型// 用FormBuilder 的 group() 方法来创建constructor(private CartService:CartService, private formBuilder: FormBuilder) {this.checkoutForm = this.formBuilder.group({name:\'\',address:\'\'});}ngOnInit(): void {this.items = this.CartService.getItems();}//提交完之后重置该表单onSubmit(customerData){console.warn(\'Your order has been submitted\',customerData);this.items = this.CartService.clearCart();this.checkoutForm.reset();}}