以下是一个基本的Angular 5购物车示例:
首先,需要创建一个名为shopping-cart
的组件,可以使用以下命令生成:
ng generate component shopping-cart
在shopping-cart.component.html
文件中,添加以下代码:
购物车
- {{ item.name }} - {{ item.price }}
总价: {{ getTotalPrice() }}
在shopping-cart.component.ts
文件中,添加以下代码:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-shopping-cart',
templateUrl: './shopping-cart.component.html',
styleUrls: ['./shopping-cart.component.css']
})
export class ShoppingCartComponent implements OnInit {
items: any[] = [
{ name: '商品1', price: 10 },
{ name: '商品2', price: 20 },
{ name: '商品3', price: 30 }
];
constructor() { }
ngOnInit() {
}
getTotalPrice(): number {
let total = 0;
for (let item of this.items) {
total += item.price;
}
return total;
}
clearCart(): void {
this.items = [];
}
}
最后,在app.component.html
文件中,添加以下代码来使用shopping-cart
组件:
现在,当你运行应用时,你将看到一个简单的购物车界面,显示了商品列表、总价格,并提供了一个清空购物车的按钮。