Nomura Nori
Nomura Nori

Reputation: 5167

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?

Upvotes: 13

Views: 22053

Answers (2)

Sajeetharan
Sajeetharan

Reputation: 222582

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

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

DEMO

Upvotes: 26

Ricardo
Ricardo

Reputation: 2487

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

Upvotes: 6

Related Questions