Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 582
Nomura Nori Avatar asked Feb 24 '18 03:02

Nomura Nori


People also ask

How do I add a variable to a template?

Choose Template > New Variable from the editor toolbar (or choose an existing variable to add it to the page) Enter a name for the variable. Press Enter (by default this will create a single-line text input field)

How do I declare a template reference variable in component?

To get started using template reference variables, simply create a new Angular component or visit an existing one. To create a template reference variable, locate the HTML element that you want to reference and then tag it like so: #myVarName .

How do you declare a variable in HTML Angular?

You can declare variables in html code by using a template element in Angular 2 or ng-template in Angular 4+. Templates have a context object whose properties can be assigned to variables using let binding syntax. Note that you must specify an outlet for the template, but it can be a reference to itself.


2 Answers

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

like image 71
Sajeetharan Avatar answered Oct 23 '22 05:10

Sajeetharan


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

like image 26
Ricardo Avatar answered Oct 23 '22 07:10

Ricardo