
//components/header//data.tsvar cartList:object = [ { "isSelected": true, "productCover": "https://img3.doubanio.com/view/subject/m/public/s33510542.jpg", "productName": "纸上行舟", "productInfo": "青年作者黎幺短篇小说首度结集", "productPrice": 57.33, "productCount": 3, "id": "0001" }, { "isSelected": true, "productCover": "https://img3.doubanio.com/view/subject/m/public/s33497735.jpg", "productName": "我可能得抑郁症了!舟", "productInfo": "青年作者黎幺短篇小说首度结集", "productPrice": 54.26, "productCount": 2, "id": "0002" }, { "isSelected": true, "productCover": "https://img3.doubanio.com/view/subject/m/public/s33474961.jpg", "productName": "绕日飞行", "productInfo": "驯马、飞行、成长、爱情", "productPrice": 22.67, "productCount": 3, "id": "0003" } ]export default cartList;
//.html<div class="wrap"> <h1 class="head">购物车</h1> <nz-table #basicTable> <thead> <tr> <th> 全选 <input type="checkbox" [(ngModel)]="checked" (change)="handleChange($event)"> </th> <th>商品</th> <th>单价</th> <th>数量</th> <th>小计</th> <th>操作</th> </tr> </thead> <tbody *ngFor="let item of cartList"> <tr> <td> <input type="checkbox" (change)="onChange(item.isSelected)" [(ngModel)]="item.isSelected"> </td> <td class="cover-name"> <img class="cover" src={{item.productCover}} alt=""> <p>{{item.productName}}</p> </td> <td>¥{{item.productPrice}}</td> <td> <nz-input-number [(ngModel)]="item.productCount" [nzMin]="1" [nzMax]="10" [nzStep]="1"></nz-input-number> </td> <td>¥{{subTotal(item.productPrice,item.productCount)}}</td> <td> <button nz-button nzType="danger" (click)="handleClick(item)">删除</button> </td> </tr> </tbody> </nz-table> <h2 class="total">总价:¥{{sum(total)}}</h2></div>
//.tsimport { Component, OnInit } from '@angular/core';import cartList from './data'@Component({ selector: 'app-header', templateUrl: './header.component.html', styleUrls: ['./header.component.css']})export class HeaderComponent implements OnInit { public cartList:any = cartList; public checked:boolean=true; constructor() { } ngOnInit() { } handleChange(){ this.cartList.forEach(item=>item.isSelected=this.checked) } onChange(){ this.checked=this.cartList.every(item=>item.isSelected) } subTotal(a,b){ return (a*b).toFixed(2) } sum(){ var total = 0; this.cartList.forEach(item=>{ if(item.isSelected){ total = item.productCount*item.productPrice+total; } }) return total.toFixed(2); } handleClick(item){ console.log(item); var cartList = this.cartList.filter(value=>value!==item); this.cartList = cartList; // for(let i = 0; i < this.cartList.length; ++i){ // if (this.cartList[i].id === id) { // this.cartList.splice(i,1); // } // } }}
//.css.wrap{ width: 100%;}.head{ text-align: center; color: brown;}.cover{ width: 80px; margin-right: 10px;}.cover-name{ display: flex; align-items: center;}.total{ color: brown; position: fixed; bottom: 0; z-index: 10;}
//app.component.html<app-header></app-header>