简体   繁体   English

Angular:模板中的局部变量可能吗?

[英]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.我认为 foo 必须被评估 2 次。 First for the ngIf and then for the value of it.首先是 ngIf,然后是它的值。 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??有没有一种方法可以定义局部变量(在模板内部?-我知道 class 内部有一个变量,但这不是问题所在)所以我只能对它求值一次?

eg sort of例如某种

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

the *ngIf allow you asign the result of a function to a variable. *ngIf允许您将 function 的结果分配给变量。 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 eg this has no importance).问题是当 function 的结果为 false、null、undefined 或“”时,因为 span 不是渲染器(在你的例子中这并不重要)。 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考虑到在这种情况下,whe 可以创建一个 object“on fly”,其属性“value”为 function 的值。因此 *ngIf 始终是 fullfilled

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

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

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