填寫這份《一分鐘調查》,幫我們(開發組)做得更好!去填寫Home

使用表單進行使用者輸入

Using forms for user input

本指南基於“入門課程”基本 Angular 應用中的第三步“管理資料”

This guide builds on the Managing Data step of the Getting Started tutorial, Get started with a basic Angular app.

本節將引導你新增基於表單的結賬功能,以收集使用者資訊作為結賬資訊的一部分。

This section walks you through adding a form-based checkout feature to collect user information as part of checkout.

定義結帳表單模型

Define the checkout form model

此步驟說明如何在元件類別中建立結帳表單模型。表單模型決定表單的狀態。

This step shows you how to set up the checkout form model in the component class. The form model determines the status of the form.

  1. 開啟 cart.component.ts

    Open cart.component.ts.

  2. @angular/forms 套件匯入 FormBuilder。此服務提供了用來產生控制元件的便捷方法。

    Import the FormBuilder service from the @angular/forms package. This service provides convenient methods for generating controls.

    src/app/cart/cart.component.ts
          
          import { Component } from '@angular/core';
    import { FormBuilder } from '@angular/forms';
    
    import { CartService } from '../cart.service';
        
  3. CartComponentconstructor() 中注入 FormBuilder 服務。該服務是你已經匯入過的 ReactiveFormsModule 模組的一部分。

    Inject the FormBuilder service in the CartComponent constructor(). This service is part of the ReactiveFormsModule module, which you've already imported.

    src/app/cart/cart.component.ts
          
          export class CartComponent {
      constructor(
        private cartService: CartService,
        private formBuilder: FormBuilder,
        ) {}
    }
        
  4. 要收集使用者的姓名和地址,請使用 FormBuildergroup() 方法來把 checkoutForm 屬性設定為一個包含 nameaddress 欄位的表單模型。

    To gather the user's name and address, use the FormBuilder group() method to set the checkoutForm property to a form model containing name and address fields.

    src/app/cart/cart.component.ts
          
          export class CartComponent {
      items = this.cartService.getItems();
      checkoutForm = this.formBuilder.group({
        name: '',
        address: ''
      });
      constructor(
        private cartService: CartService,
        private formBuilder: FormBuilder,
        ) {}
    }
        
  5. 定義一個 onSubmit() 方法來處理表單。該方法允許使用者提交其姓名和地址。此外,此方法會使用 CartServiceclearCart() 方法重置表單並清除購物車。

    Define an onSubmit() method to process the form. This method allows users to submit their name and address. In addition, this method uses the clearCart() method of the CartService to reset the form and clear the cart.

    整個購物車元件類別如下:

    The entire cart component class is as follows:

    src/app/cart/cart.component.ts
          
          import { Component } 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 {
      items = this.cartService.getItems();
      checkoutForm = this.formBuilder.group({
        name: '',
        address: ''
      });
      constructor(
        private cartService: CartService,
        private formBuilder: FormBuilder,
        ) {}
    
      onSubmit(): void {
        // Process checkout data here
        this.items = this.cartService.clearCart();
        console.warn('Your order has been submitted', this.checkoutForm.value);
        this.checkoutForm.reset();
      }
    }
        

建立結帳表單

Create the checkout form

使用以下步驟在“購物車”檢視的底部新增一個結帳表單。

Use the following steps to add a checkout form at the bottom of the Cart view.

  1. cart.component.html 的底部,新增一個 HTML <form> 元素和一個 Purchase 按鈕。

    At the bottom of cart.component.html, add an HTML <form> element and a Purchase button.

  2. 使用 formGroup 屬性繫結將 checkoutForm 繫結到 HTML 中的 <form> 標籤。

    Use a formGroup property binding to bind checkoutForm to the HTML <form>.

    src/app/cart/cart.component.html
          
          <form [formGroup]="checkoutForm">
    
      <button class="button" type="submit">Purchase</button>
    
    </form>
        
  3. form 標籤上,使用 ngSubmit 事件繫結來偵聽表單提交,並以 checkoutForm 的值為引數呼叫 onSubmit() 方法。

    On the form tag, use an ngSubmit event binding to listen for the form submission and call the onSubmit() method with the checkoutForm value.

    src/app/cart/cart.component.html (cart component template detail)
          
          <form [formGroup]="checkoutForm" (ngSubmit)="onSubmit()">
    </form>
        
  4. 新增 nameaddress<input> 欄位,每個欄位都有一個 formControlName 屬性,該屬性繫結到 checkoutForm 表單控制元件,以將 nameaddress 繫結到其 <input> 欄位。完整的元件如下:

    Add <input> fields for name and address, each with a formControlName attribute that binds to the checkoutForm form controls for name and address to their <input> fields. The 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()">
    
      <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 review their items, enter their name and address, and submit their purchase.

要確認提交,請開啟控制檯以檢視包含你所提交的名稱和地址的物件。

To confirm submission, open the console to see an object containing the name and address you submitted.

下一步是什麼

What's next

你現在有了一個具備產品目錄、購物車和結帳功能的完整線上商店應用。

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.