定义checkout form model
-
打开cart.component.ts
-
注入FormBuilder service到CartComponent
constructor( private readonly cartService: CartService, private readonly formBuilder: FormBuilder ){} -
使用FormBuilder group()方法来设置checkoutForm的属性,包括name和address
checkoutForm = this.formBuilder.group({ name: '', address: '' }); -
定义onSubmit方法,这个方法允许用户提交name和address。另外,调用CartService的clearCart方法来清空购物车
this.items = this.cartService.clearCart(); console.warn('Your order has been submitted', this.checkoutForm.value); this.checkoutForm.reset(); }
创建checkout form
-
在cart.component.html的底部,添加一个HTML <form> 元素和一个Purchase按钮
-
使用formGroup属性来绑定checkoutForm和HTML<form>
<form [formGroup]="checkoutForm"> <button type="submit">Purchase</button> </form>
PS: 记得在app.module.ts中导入ReactiveFormsModule
```
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule,
ReactiveFormsModule
],
```
3. 绑定onSubmit方法到ngSubmit属性,为属性name和address添加输入框,并绑定formControlName属性,这个属性会绑定checkoutForm model到页面上的控件
```
<form [formGroup]="checkoutForm" (ngSubmit)="onSubmit()" class="inputForm">
<div>
<label for="name">Name</label>
<input id="name" type="text" formControlName="name">
</div>
<div>
<label for="address">Address</label>
<input id="address" type="text" formControlName="address">
</div>
<button type="submit">Purchase</button>
</form>
```
4. 最终的结果如下