'Angular: local variable in template possible?

Lets imagine this simple example. Display a string if its length is even.

<span *ngIf="foo ('abcd').length > 0">{{ foo ('abcd') }}</span>



foo (str : string) : string
{
    if (str.length % 2 == 0)
    {
        return str;
    }
    return "";
}

I think foo must be evaluated 2 times. First for the ngIf and then for the value of it. Is there a way I can define a local variable (inside of the template! - I am aware of having a variable inside of the class but thats not the question) so I can only have it evaluated once??

e.g. sort of

<span *ngIf="let myvar = foo ('abcd'); return myvar.length % 2 == 0">{{ myvar }}</span>


Solution 1:[1]

the *ngIf allow you asign the result of a function to a variable. Some like

<span *ngIf="fool('abcd') as value">
{{value}}
</span>

The problem is when the result of the function is false, null, undefined or "", because the span is not renderer (in your e.g. this has no importance). To take account in this case whe can create an object "on fly" with a property "value" whit the value of the function. So the *ngIf is always fullfilled

<span *ngIf="{value:fool('abcd')} as obj">
{{obj.value}}
</span>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Eliseo