多个输入推送到数组 [Angular]

时间:2021-07-21 22:00:32

标签: javascript html angular typescript

我正在尝试制作一个我喜欢练习的预算应用程序的副本。基本的想法是你有你的月收入,在你下面加上你一个月得到的薪水。由于我需要计算总收入,因此我将每个薪水的输入使用相同的引用发送到相同的数组。 我想弄清楚如何在不为每个薪水创建变量的情况下让输入进入同一个数组。不确定这是否可能。

我似乎也无法弄清楚如何获得数组的总和。

HTML:

 <td>Paycheck 1</td>
 <td class="money">
   <input
     matInput
     class="form-control"
     type="number"
     placeholder="$0.00"
     #income
     (keydown.enter)="onIncomeInput(income.value)">
</tr>
<tr>
  <td>Paycheck 2</td>
  <td class="money">
    <input
      matInput
      class="form-control"
      type="number"
      placeholder="$0.00"
      #income
      (keydown.enter)="onIncomeInput(income.value)">
  </td>
</tr>

ts 组件:

import { Component, OnInit } from '@angular/core';
import { IncomeService } from '../services/income.service';

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

  constructor(private incomeService: IncomeService) { }

  ngOnInit(): void {
  }

  onIncomeInput(value: Number) {
    this.incomeService.incomeCalculation(value)
  }

}

ts 服务:

import { Injectable } from "@angular/core";


@Injectable({
  providedIn: 'root'
})

export class IncomeService {
  paychecks: number[] = []
  totalIncome: number
  acc = 0

  reducerSum(acc, val) {
    return acc + val
  }

  incomeCalculation(value) {
    this.paychecks.push(value)
    let total = this.paychecks.reduce(this.reducerSum)
    console.log(total)
  }
}

0 个答案:

没有答案