简体   繁体   English

如何在Angular模板中声明变量?

[英]How to declare variable in template of Angular?

This is source code 这是源代码

<div>
{{ getActualData() }}
</div>
<div>
{{ getVirtualData() }}
</div>
<div>
 {{ getActualData() - getVirtualData() }}
</div>

This is what I want. 这就是我要的。

<div>
{{ actual = getActualData() }}
</div>
<div>
{{ virtual = getVirtualData() }}
</div>
<div>
{{ actual - virtual }}
</div>

Because two functions are complex, I would like to save data temporarily and calculate difference shortly. 由于两个函数都很复杂,我想暂时保存数据并尽快计算差异。 Is there any way to do this? 有没有办法做到这一点?

You can declare variable in template using let that will evaluate the function and get the result , using ngIf to actually check if the value is there and assign to the variable 您可以使用let来声明模板中的变量,它将评估函数并获得结果,使用ngIf实际检查值是否存在并分配给变量

<div *ngIf="getActualData(); let actual" > 
<div *ngIf="getVirtualData(); let virtual" > 
 {{actual - virtual}}
</div>

DEMO DEMO

you can try : 你可以试试 :

    <div *ngIf="getActualData(); let actual">
      <div *ngIf="getVirtualData(); let virtual">
        {{ actual - virtual }}
      </div>
    </div>
    </div>

this is a workaround but should work 这是一种解决方法但应该有效

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM