简体   繁体   中英

Angular Template Scope Variable

Is there a feature in Angular to declare a variable like in ngFor?

I want to reduce the calling and computing of same values. I could use the getValue() method also below for 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.

Additional: Without create new directive. Maybe wrap the value in an array to use 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:

<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.

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