填写这份《一分钟调查》,帮我们(开发组)做得更好!去填写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.