0

I have a question about declaring temporary variables in Angular template to use it for multiple element (childs) like: (Idea / Expected)

<ng-container *ngVar="let theValue = item.getValue()">
  <div>{{ theValue }}</div>
  <div [class.foo]="theValue == 42">foo</div>
</ng-container>

I already have a workaround for this. Just wrap the value in a array and use ngFor like: (Workaround)

<ng-container *ngFor="let theValue of [item.getValue()]">
  <div>{{ theValue }}</div>
  <div [class.foo]="theValue == 42">foo</div>
</ng-container>

But this is a bit dirty. - Is there an official solution?

My idea is to reduce the computing of the value over and over again for the same value. I just want to reuse the computed value for multiple childs and / or attributes.

I do not want to compute getValue() every time. Because I get the same value anyway. To hold the value temporary in a group element it can improve the performance and readability.

It should be possible without a custom directive. I mean to have seen something like this before.

Domske
  • 4,795
  • 2
  • 20
  • 35
  • Not entirely a duplicate, but the answer given there, answers your question. There is no `ngVar`. You can create it yourself, or use `*ngIf="item.getValue() as value"`. But this will only work if the value is truthy – Poul Kruijt Feb 05 '19 at 09:34
  • So my workaround with ngFor [value] is still better. Does not depend on boolean evaluation. But ok. I'll watch this feature in futur and check out the git repository of Angular. Maybe I'll add this in an official way. ll'see. - For me it's not a duplicate. In my opinion it's a very important feature for Angular and should be prioritized highly. ... But whatever, this should moved to Github. – Domske Feb 05 '19 at 09:56
  • I agree with you. This should be in the library. I don't know what their reasoning is that it's not. Maybe they don't want to clutter the template. The problem with your implementation is that it creates a new array on every check, as far as I know. I believe github already has a feature request for this, you should check it out – Poul Kruijt Feb 05 '19 at 10:13

1 Answers1

0

One possible solution is to 'cache' the return value of getValue(). This technique is called memoization. It works only on pure functions, meaning that for the same inputs, the output is always the same, and when function has no side effect.

You can use a decorator to achieve this in a straightforward manner, here is a project that might be useful to you: https://github.com/darrylhodgins/typescript-memoize.

Hoff
  • 38,776
  • 17
  • 74
  • 99