36

Is it possible to assign (areShipsExpanded$ | async) to variable without *ngIf? Because in case that this is flag true/false when I have: *ngIf="(areShipsExpanded$ | async) as flag" then button is not displaying in case of false.

And I would like something like this:

<button *let="(areShipsExpanded$ | async) as flag"
   (click)="expandAllShips(flag)">{{(flag ? "Collapse" : "Expand"}}
</button>
DiPix
  • 5,755
  • 15
  • 61
  • 108

3 Answers3

53

Little late to the party here but I found a great example of how to do this from this medium article

You still use *ngIf but you make sure that it always evaluates truthy by passing in a new object with your observable value as a property.

<div *ngIf="{value1: myObs$ | async} as valuesObj">
    {{ valuesObject.value1 }}
</div>

IMO this is still a little hacky but much less hacky than the other answer or creating your own *ngLet directive.

As mentioned in the article, this is also a good way to group together multiple observable values in multiple object properties so you don't have to have multiple async statements or nested <ng-container> elements.

mcheah
  • 1,209
  • 11
  • 28
  • There's a number of `*ngLet` implementations out there, but this saved adding another dependency – Drenai Mar 18 '22 at 23:22
15

You can do it using ng-template and ng-container

<ng-template #myTempl let-flag="areShipsExpand">
      <button
   (click)="expandAllShips(flag)">{{flag ? "Collapse" : "Expand"}}
  </button>
</ng-template>

<ng-container *ngTemplateOutlet="myTempl; context:{areShipsExpand: areShipsExpanded$ | async}"></ng-container>

DEMO

Amit Chigadani
  • 28,482
  • 13
  • 80
  • 98
8

Use the *ngrxLet directive from @ngrx/component

<ng-container *ngrxLet="observableNumber$ as n">
   <app-number [number]="n">
   </app-number>
</ng-container>

Visibility of the element containing the ngrxLet directive is not affected by the value of the observable expression.

Neutrino
  • 8,496
  • 4
  • 57
  • 83