p2.component.ts 1.57 KB
Newer Older
李彥志's avatar
李彥志 committed
1
import { Component, OnInit } from '@angular/core';
李彥志's avatar
李彥志 committed
2
import { Data } from './data';
李彥志's avatar
李彥志 committed
3 4 5 6 7 8 9 10 11 12 13 14 15 16

@Component({
  selector: 'app-p2',
  templateUrl: './p2.component.html',
  styleUrls: ['./p2.component.css']
})
export class P2Component implements OnInit {

    name = '';

    price = '';

    quantity = '';

李彥志's avatar
李彥志 committed
17
    datas: Data[] = [];
李彥志's avatar
李彥志 committed
18

19
    result: any;
20
    total: any;
李彥志's avatar
李彥志 committed
21

李彥志's avatar
李彥志 committed
22 23
    message = '';

24

李彥志's avatar
李彥志 committed
25 26 27 28
    buildMessage(): void {
    if (this.name !== null && this.price !== null && this.quantity !== null &&
        this.name !== undefined && this.price !== undefined && this.quantity !== undefined
      ) {
29 30
        this.message = '你購買' + this.name + '商品,單價' + this.price + '元,數量'
        + this.quantity + '元,共計NT$';
李彥志's avatar
李彥志 committed
31 32 33 34
        }
    }

    addData(): void {
李彥志's avatar
李彥志 committed
35 36 37 38 39

   // 防呆,避免名稱或內容是空值時也可以留言
    if (
      !this.name.trim() && !this.price.trim() && !this.quantity.trim()
    ) {
李彥志's avatar
李彥志 committed
40
      return alert('項目資訊沒填好');
李彥志's avatar
李彥志 committed
41 42
    }
    // 用名稱跟內容產生一個留言的資料物件
李彥志's avatar
李彥志 committed
43 44
    const data = new Data(this.name, this.price, this.quantity);

李彥志's avatar
李彥志 committed
45
    // 將留言的資料物件放進容器裡
李彥志's avatar
李彥志 committed
46 47
    this.datas.push(data);

李彥志's avatar
李彥志 committed
48 49

  }
李彥志's avatar
李彥志 committed
50

51 52 53
    totalPrice(): void {
      for (
        const i = 0; i < this.datas.length; i++
54 55
      ) { const data = this.datas;
        this.result = this.result + data[i].total;
56
      }
57
      return this.result;
李彥志's avatar
李彥志 committed
58 59
    }

李彥志's avatar
李彥志 committed
60
    deleteItem(name, i): void {
李彥志's avatar
李彥志 committed
61
      console.log(name);
李彥志's avatar
李彥志 committed
62
      this.datas.splice(i, 1);
李彥志's avatar
李彥志 committed
63 64
    }

65 66 67 68 69
    cleanItem(name, i): void {
      console.log(name);
      this.datas.splice(i)
    }

李彥志's avatar
李彥志 committed
70 71 72 73 74 75
  constructor() { }

  ngOnInit() {
  }

}