import { Component, OnInit } from '@angular/core'; import { Data } from './data'; @Component({ selector: 'app-p2', templateUrl: './p2.component.html', styleUrls: ['./p2.component.css'] }) export class P2Component implements OnInit { name = ''; price = ''; quantity = ''; datas: Data[] = []; // result = 0; total: any; message = ''; // buildMessage(): void { // if (this.name !== null && this.price !== null && this.quantity !== null && // this.name !== undefined && this.price !== undefined && this.quantity !== undefined // ) { // this.message = '你購買' + this.name + '商品,單價' + this.price + '元,數量' // + this.quantity + '元,共計NT$'; // } // } addData(): void { // 防呆,避免名稱或內容是空值時也可以留言 if ( !this.name.trim() && !this.price.trim() && !this.quantity.trim() ) { return alert('項目資訊沒填好'); } // 用名稱跟內容產生一個留言的資料物件 const data = new Data(this.name, this.price, this.quantity); // 將留言的資料物件放進容器裡 this.datas.push(data); } totalPrice() { let result = 0; for ( let i = 0; i < this.datas.length; i++ ) { const data = this.datas[i]; result = result + data.total; } return result; } deleteItem(name, i): void { console.log(name); this.datas.splice(i, 1); } cleanItem(name, i): void { console.log(name); this.datas.splice(i) } constructor() { } ngOnInit() { } }