新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
創(chuàng)新互聯(lián)Angular教程:Angular使用表單進(jìn)行用戶輸入
使用表單進(jìn)行用戶輸入
本指南基于“入門教程”基本 Angular 應(yīng)用中的第三步“管理數(shù)據(jù)”。

創(chuàng)新互聯(lián)專注于古田網(wǎng)站建設(shè)服務(wù)及定制,我們擁有豐富的企業(yè)做網(wǎng)站經(jīng)驗(yàn)。 熱誠為您提供古田營銷型網(wǎng)站建設(shè),古田網(wǎng)站制作、古田網(wǎng)頁設(shè)計(jì)、古田網(wǎng)站官網(wǎng)定制、成都小程序開發(fā)服務(wù),打造古田網(wǎng)絡(luò)公司原創(chuàng)品牌,更為您提供古田網(wǎng)站排名全網(wǎng)營銷落地服務(wù)。
本節(jié)將引導(dǎo)你添加基于表單的結(jié)賬功能,以收集用戶信息作為結(jié)賬信息的一部分。
定義結(jié)帳表單模型
此步驟說明如何在組件類中建立結(jié)帳表單模型。表單模型決定表單的狀態(tài)。
- 打開 ?
cart.component.ts? 。 - 從 ?
@angular/forms? 包導(dǎo)入 ?FormBuilder?。此服務(wù)提供了用來生成控件的便捷方法。 - 在 ?
CartComponent?的 ?constructor()? 中注入 ?FormBuilder?服務(wù)。該服務(wù)是你已經(jīng)導(dǎo)入過的 ?ReactiveFormsModule?模塊的一部分。 - 要收集用戶的姓名和地址,請(qǐng)使用 ?
FormBuilder?的 ?group()? 方法來把 ?checkoutForm?屬性設(shè)置為一個(gè)包含 ?name?和 ?address?字段的表單模型。 - 定義一個(gè) ?
onSubmit()? 方法來處理表單。該方法允許用戶提交其姓名和地址。此外,此方法會(huì)使用 ?CartService?的 ?clearCart()? 方法重置表單并清除購物車。
import { Component } from '@angular/core';
import { FormBuilder } from '@angular/forms';
import { CartService } from '../cart.service';
export class CartComponent {
constructor(
private cartService: CartService,
private formBuilder: FormBuilder,
) {}
}
export class CartComponent {
items = this.cartService.getItems();
checkoutForm = this.formBuilder.group({
name: '',
address: ''
});
constructor(
private cartService: CartService,
private formBuilder: FormBuilder,
) {}
}
整個(gè)購物車組件類如下:
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();
}
}
創(chuàng)建結(jié)帳表單
使用以下步驟在“購物車”視圖的底部添加一個(gè)結(jié)帳表單。
- 在 ?
cart.component.html? 的底部,添加一個(gè) HTML ?? 元素和一個(gè) Purchase 按鈕。 - 使用 ?
formGroup?屬性綁定將 ?checkoutForm?綁定到 HTML 中的 ?? 標(biāo)簽。 - 在 ?
form?標(biāo)簽上,使用 ?ngSubmit? 事件綁定來偵聽表單提交,并以 ?checkoutForm?的值為參數(shù)調(diào)用 ?onSubmit()? 方法。 - 添加 ?
name?和 ?address?的 ?? 字段,每個(gè)字段都有一個(gè) ?formControlName?屬性,該屬性綁定到 ?checkoutForm?表單控件,以將 ?name?和 ?address?綁定到其 ?? 字段。完整的組件如下:
Cart
{{ item.name }}
{{ item.price | currency }}
將少量物品放入購物車后,用戶可以查看他們的物品,輸入他們的姓名和地址,然后提交購買的商品。
要確認(rèn)提交,請(qǐng)打開控制臺(tái)以查看包含你所提交的名稱和地址的對(duì)象。
網(wǎng)頁標(biāo)題:創(chuàng)新互聯(lián)Angular教程:Angular使用表單進(jìn)行用戶輸入
轉(zhuǎn)載注明:http://www.5511xx.com/article/copsoog.html


咨詢
建站咨詢
