简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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