表單
Using forms for user input
當管理資料結束時,這個線上商店應用有了一個商品名錄和一個購物車。
At the end of Managing Data, the online store application has a product catalog and a shopping cart.
本節將帶你透過新增基於表單的結帳功能來完成該應用。你還將建立一個表單來收集使用者資訊,作為結賬過程的一部分。
This section walks you through adding a form-based checkout feature to collect user information as part of checkout.
Angular 中的表單
Forms in Angular
Angular 中的表單建立在標準 HTML 表單功能之上,以幫助你建立自訂表單控制元件和輕鬆的驗證體驗。Angular 響應式表單有兩個部分:元件中那些用於儲存和管理表單的物件,以及表單在範本中的視覺化。
Forms in Angular build upon the standard HTML forms to help you create custom form controls and easy validation experiences. There are two parts to an Angular Reactive 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.
定義結帳的表單模型
Define the checkout form model
首先,你要設定一個結賬的表單模型。在元件類別中定義它,把它作為表單狀態的真相之源(source of truth)。
First, set up the checkout form model. Defined in the component class, the form model is the source of truth for the status of the form.
開啟
cart.component.ts
。Open
cart.component.ts
.Angular 的
FormBuilder
服務為產生控制元件提供了方便的方法。和你使用過的其它服務一樣,你需要匯入並注入該服務,然後才能使用它:Angular's
FormBuilder
service provides convenient methods for generating controls. As with the other services you've used, you need to import and inject the service before you can use it:從
@angular/forms
套件中匯入FormBuilder
服務。Import the
FormBuilder
service from the@angular/forms
package.src/app/cart/cart.component.ts import { Component, OnInit } from '@angular/core'; import { FormBuilder } from '@angular/forms'; import { CartService } from '../cart.service';
ReactiveFormsModule
中提供了FormBuilder
服務,它已經在之前修改過的AppModule
(位於app.module.ts
)中匯入過了。The
ReactiveFormsModule
provides theFormBuilder
service, whichAppModule
(inapp.module.ts
) already imports.注入這個
FormBuilder
服務。Inject the
FormBuilder
service.src/app/cart/cart.component.ts export class CartComponent implements OnInit { items; constructor( private cartService: CartService, private formBuilder: FormBuilder, ) { } ngOnInit() { this.items = this.cartService.getItems(); } }
還是在
CartComponent
類別中,定義checkoutForm
屬性來儲存表單模型。Still in the
CartComponent
class, define thecheckoutForm
property to store the form model.src/app/cart/cart.component.ts export class CartComponent implements OnInit { items; checkoutForm; }
要想手機使用者的姓名和地址,把
checkoutForm
屬性設定為一個包含name
和address
欄位的表單模型。使用FormBuilder
的group()
方法來建立它,把該語句加入建構函式的花括號{}
中間。To gather the user's name and address, set the
checkoutForm
property with a form model containingname
andaddress
fields, using theFormBuilder
group()
method. Add this between the curly braces,{}
, of the constructor.src/app/cart/cart.component.ts 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(); } }
在結帳過程中,使用者要提交他們的姓名和地址。在提交訂單之後,表單應該重置,購物車應該清空。
For the checkout process, users need to submit their name and address. When they submit their order, the form should reset and the cart should clear.
在
cart.component.ts
中,定義一個onSubmit()
方法來處理表單。使用CartService
clearCart()
方法清空購物車專案,並在提交完之後重置該表單。在實際應用中,此方法也會把資料提交給外部伺服器。 整個購物車元件類別如下所示:In
cart.component.ts
, define anonSubmit()
method to process the form. Use theCartService
clearCart()
method to empty the cart items and reset the form after its submission. In a real-world app, this method would also submit the data to an external server. The entire cart component class is as follows:
src/app/cart/cart.component.ts import { Component, OnInit } from '@angular/core'; import { FormBuilder } from '@angular/forms'; import { CartService } from '../cart.service'; @Component({ selector: 'app-cart', templateUrl: './cart.component.html', styleUrls: ['./cart.component.css'] }) 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(); } onSubmit(customerData) { // Process checkout data here this.items = this.cartService.clearCart(); this.checkoutForm.reset(); console.warn('Your order has been submitted', customerData); } }
現在,你已經在元件類別中定義了表單模型,還要建立一個結賬表單,以便把該模型對映到檢視中。
Now that you've defined the form model in the component class, you need a checkout form to reflect the model in the view.
建立結帳表單
Create the checkout form
使用下列步驟在“購物車”檢視的底部新增一個結帳表單。
Use the following steps to add a checkout form at the bottom of the "Cart" view.
開啟
cart.component.html
。Open
cart.component.html
.在範本的底部,新增一個空的 HTML 表單來捕獲使用者資訊。
At the bottom of the template, add an HTML form to capture user information.
使用
formGroup
屬性繫結把checkoutForm
繫結到範本中的form
標籤上。還要提供一個 “Purchase” 按鈕來提交表單。Use a
formGroup
property binding to bind thecheckoutForm
to theform
tag in the template. Also include a "Purchase" button to submit the form.src/app/cart/cart.component.html <form [formGroup]="checkoutForm"> <button class="button" type="submit">Purchase</button> </form>
在
form
標籤上,使用ngSubmit
事件繫結來監聽表單提交,並使用checkoutForm
值呼叫onSubmit()
方法。On the
form
tag, use anngSubmit
event binding to listen for the form submission and call theonSubmit()
method with thecheckoutForm
value.src/app/cart/cart.component.html (cart component template detail) <form [formGroup]="checkoutForm" (ngSubmit)="onSubmit(checkoutForm.value)"> </form>
為
name
和address
新增輸入欄位。使用formControlName
屬性繫結來把checkoutForm
表單控制元件中的name
和address
繫結到它們的輸入欄位。最終的完整版元件如下:Add input fields for
name
andaddress
. Use theformControlName
attribute binding to bind thecheckoutForm
form controls forname
andaddress
to their input fields. The final complete component is as follows:src/app/cart/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> <form [formGroup]="checkoutForm" (ngSubmit)="onSubmit(checkoutForm.value)"> <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 class="button" type="submit">Purchase</button> </form>
往購物車中放入幾件商品之後,使用者可以檢視這些商品,輸入自己的姓名和地址,進行購買:
After putting a few items in the cart, users can now review their items, enter their name and address, and submit their purchase:

要檢查這次提交,請開啟控制檯,你會在那裡看到一個包含你提交的姓名和地址的物件。
To confirm submission, open the console where you should see an object containing the name and address you submitted.
下一步
Next steps
恭喜!你有了一個完整的線上商店應用,它具有商品名錄,購物車和結賬功能。
Congratulations! You have a complete online store application with a product catalog, a shopping cart, and a checkout function.
繼續瀏覽“部署”部分,把你的應用轉移到本地開發、部署到 Firebase 或你自己的伺服器。
Continue to the "Deployment" section to move to local development, or deploy your app to Firebase or your own server.