Angular2:在#ngFor中分配组件字段

时间:2017-02-22 15:12:08

标签: html angular typescript

我有这样的组成部分:

function myFunction() {

var sheet1 = SpreadsheetApp.openById("ID").getSheetByName("Sheet1");
var sheet2 = SpreadsheetApp.openById("ID").getSheetByName("Sheet2");

var date1 = sheet1.getRange(1, 2, sheet1.getLastRow()).getValues(); //getRange(row, column, numRows, numColumns)
var date2 = sheet2.getRange(1, 2, sheet1.getLastRow()).getValues();

  for (var i = 0; i < date1.length; i++){
      test = sheet2.getRange(i+1, 2).getValue()
      test1 = sheet1.getRange(i+1, 2).getValue()
      if (test != test1 ) {
  var data1 = sheet1.getRange(i+1,2).getValue();
  var data2 = sheet1.getRange(i+1,3).getValues();
  var data3 = sheet1.getRange(i+1,4).getValue();
  sheet2.getRange(i+1, 2).setValue(data1);
  sheet2.getRange(i+1, 3).setValue(data2);
  sheet2.getRange(i+1, 4).setValue(data3);
    }
  }
}

还有这样的模板:

 @Component({
        selector: "expenses-component",
        templateUrl: "expenses.html"
    })
    export default class ExpensesComponent {
        private expenses: [] = [{name: "Foo", amount: 100}, {name: "Bar", amount: 200}];
        private totalAmount: number = 0;
    }

我需要计算<h2 class="sub-header">Total: {{total | currency:"USD":true}}</h2> <div class="table-responsive"> <table class="table table-hover table-condensed"> <thead> <tr> <th>#</th> <th>Name</th> <th>Amount</th> </tr> </thead> <tbody> <tr *ngFor="let expense of expenses | orderByDate; let id = index"> <td>{{id + 1}}</td> <td>{{expense.name}}</td> <td>{{expense.amount | currency:"USD":true}}</td> </tr> </tbody> </table> </div> ,但我无法在没有在打字稿代码中提供另一个for循环的情况下弄清楚如何执行此操作,因此有可能在上面的内容中初始化totalAmount total += expense.amount循环?

2 个答案:

答案 0 :(得分:1)

据我所知,这是不可能的。您可以通过创建自定义管道来实现它,该管道将遍历数组并返回totalAmount。作为参数,您可以传递要用作值的键的名称。

例如:

import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
   name: 'totalAmount'
})

export class totalAmount implements PipeTransform {
    transform(value:any, key:string):any {
       if(value){
          let total = 0;

          for(let i in value){
             total = total + value[i][key];    
          }            

          return total;
    }
    return value;
    }}

然后你可以从html中调用它:

<div>{{expenses | totalAmount:"amount"}}</div>

答案 1 :(得分:1)

你可以使totalAmount成为一个get()方法并将其返回吗?

private get totalAmount() {
    let total = 0;
    for (let item in this.expenses) {
        total += item.amount;
    }
    return total;
}