简体   繁体   English

角度模板范围变量

[英]Angular Template Scope Variable

Is there a feature in Angular to declare a variable like in ngFor? Angular中是否有一项功能可以像ngFor中一样声明变量?

I want to reduce the calling and computing of same values. 我想减少相同值的调用和计算。 I could use the getValue() method also below for getFormatString. 我也可以在下面将getValue()方法用于getFormatString。 But I want to optimize the performance. 但是我想优化性能。

I expected something like: 我期望像这样:

<ion-item [color]="value < 0 ? 'danger' : 'success'" *ngInit="let value = getValue()">
  <h3>Value</h3>
  <p item-end>{{ getFormatString(value) }}</p>
</ion-item>

Actually I have to set the same method to get the same value every time. 实际上,我必须设置相同的方法来每次获得相同的值。 My idea is about: Fetch the value once, and share it for the child elements. 我的想法是:一次获取值,并将其共享给子元素。 Like ngFor, the variable is available for all other elements in the scope. 与ngFor一样,该变量可用于范围中的所有其他元素。

Additional: Without create new directive. 附加:不创建新指令。 Maybe wrap the value in an array to use ngFor? 也许将值包装在数组中以使用ngFor? But this is ugly. 但这是丑陋的。 ... I'm sure it is possible. ...我相信这是可能的。 I did this in the past. 我过去曾这样做。 But I don't know how anymore. 但是我不知道了。

One (a bit dirty) solution is to wrap it in an array and use ngFor like: 一种(有点脏)的解决方案是将其包装在数组中,并使用ngFor像这样:

<ion-item [color]="value < 0 ? 'danger' : 'success'" *ngFor="let value of [getValue()]">
  <h3>Value</h3>
  <p item-end>{{ getFormatString(value) }}</p>
</ion-item>

 *ngFor="let value of values;" {{value | formatString}} 

Transform value using custom filter. 使用自定义过滤器转换值。

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

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