10. 表单

2019-08-02  本文已影响0人  晨曦Bai

1. 定义结账表单模型

FormBuilder 服务为出创建控件提供了方便。


》 cart.component.ts


import  {  Component }  from  '@angular/core';  
import  {  FormBuilder  }  from  '@angular/forms'; 
import  {  CartService  }  from  '../cart.service';
export  class  CartComponent  {
items; 
checkoutForm;
constructor(  
private cartService:  CartService,  
private formBuilder:  FormBuilder, 
 )  { 
this.items = this.cartService.getItems();
this.checkoutForm = this.formBuilder.group({
      name: '',
      address: ''
    });
 }  
onSubmit(customerData) {
    // Process checkout data here
    console.warn('Your order has been submitted', customerData);
    this.items = this.cartService.clearCart();
    this.checkoutForm.reset();
  }
}

2. 在 checkout form


》 cart.component.html


<h3>Cart</h3>
<p>
 <a routerLink ="/shipping">Shipping Prices</[a]
</p>

 <div  class="cart-item" *ngFor="let item of items">
 <span>{{ item.name }} </span>
 <span>{{ item.price | currency }}</span>
 </div>
 <div>
 <label>Name</label>
  <input  type="text"  formControlName="name">
 </div>
<div> 
 <label>Address</label>
 <input  type="text"  formControlName="address">  </div>

<form [formGroup]="checkoutForm" (ngSubmit())="onSubmit(checkoutForm.value)">
<button class="button" type="submit">Purchase</button>
</form>
上一篇 下一篇

猜你喜欢

热点阅读