2017-03-15 57 views
0

在我的角2模板,我在的形式极其繁琐的计算:Angular 2:将数学语句分配给模板中的变量?

<td class="text-right"><strong> 
        {{((avgGrossProfitPer * addMonthlySalesVolume) + (addMonthlySalesVolume * addCarryingCostProf/100) + 
        (accessAmount + 10 + numChecks + (addMonthlySalesVolume * 0.075)) || '0') | currency:'USD':true}} 
        </strong> 
       </td> 

这里所有的变量进行input [(ngModel)]="templateName"设置。但是,我想要做的是将此计算的值设置为一个变量,因此我不必再次复制/粘贴整个公式。

我已经试过是:

<td class="text-right"><strong #monthlyroi> 
        {{((avgGrossProfitPer * addMonthlySalesVolume) + (addMonthlySalesVolume * addCarryingCostProf/100) + 
        (accessAmount + 10 + numChecks + (addMonthlySalesVolume * 0.075)) || '0') | currency:'USD':true}} 
        </strong> 
       </td> 

<!--Try to return the value of the calculation above--> 
<span>{{monthlyroi}}</span> 

然而,{{monthlyroi}}返回 “[HTML元素的对象]” 在网页上呈现的时候。

+0

你有没有考虑只是把一个函数接受你所需要的参数和返回你想要的值双花括号? – Gab

+0

我有,虽然我是新来Angular 2,所以不知道什么是最好的方法来处理这个。我试着在'app.component中写一个函数。ts'接受这些值作为参数,但是我希望每次用户更改输入时都自动更新这个值,所以我在模板中到处都有很多'(keyup)=“functionName(myparamaters)''让事情变得笨重。 – user3183717

+0

相反,您可以使用'(change)= ...'而不是'(keyup)= ...' – Gab

回答

0

您可以参考所有这些变量的事实意味着它们是组件的成员。这意味着,你可以封装复杂的计算方法中的

在您的组件,

export class MyComponent { 
....... 

    myFancyCalculation(): number { 
    return ((this.avgGrossProfitPer * this.addMonthlySalesVolume) + 
      (this.addMonthlySalesVolume * this.addCarryingCostProf/100) + 
      (this.accessAmount + 10 + this.numChecks + (this.addMonthlySalesVolume * 0.075)) || '0') 
    } 
} 

现在你可以在你的模板中使用myFancyCalculation()(适当命名的,当然)。

选择方法而不是变量的原因是,对于变量,必须在各种输入变量发生变化时手动更新该计算变量。通过使用函数,您不再需要手动同步。考虑到这个计算的大小,我可能会创建一些辅助方法来更好地封装和描述计算所做的事情。

编辑:

您可以在计算中添加变量的MyComponent的

成员变量如: 出口类MyComponent的{ ....... avgGrossProfitPer:数; addMonthlySalesVolume:number; etc ...

通过以上操作可以访问myFancyCalculation方法中的变量。

第二个选项是将myFancyCalculation更改为接受各个字段作为参数。在这种情况下,在myFancyCalculation中,您不会在变量前添加this.,因为它们只是您的方法的参数

例如, myFancyCalculation(avgGrossProfit:编号,addMonthlySalesVolume:数...等)

且模板中,

<td class="text-right"> 
    <strong> 
       {{ myFancyCalculation(avgGrossProfitPer, addMonthlySalesVolume ... etc) }} 
    </strong> 
+0

但是我需要做的是每次都调用这个计算我的一个变量的值被改变了。所以我必须在每个输入处添加'(change)=“myFancyCalculation()”'来定义我的变量吗? – user3183717

+0

您提到计算中使用的各种变量绑定到使用ngModel的输入字段?如果是这样,那么ngModel将在用户键入输入时更新单个变量值,然后Angular的变化检测将更新视图中的计算。您不必添加单独的(更改)绑定。假设你对单个变量使用ngModel – snorkpete

+0

当我编写你在'app.component.ts'中提供的函数时,我得到错误:''Property'variableName'在所有类型的'AppComponent'.'上都不存在我的变数。我不确定如何在这种情况下让它们“存在”,当我在'app.compoment.html'中用'' – user3183717