16

If I have some Observable data$, I can use as in Angular as follows:

<ng-template #loading>Loading...</ng-template>
<ng-container *ngIf="(data$ | async) as data; else loading">
  <div *ngFor="let item of data">...</div>
</ng-container>

That's really cool and useful as it avoids subscribing to data$ more than once. However, what if I want to avoid doing so but stay within the same container? Ideally, something like (the obviously not working)

<ng-container let-data="data$ | async">
  <ng-container *ngIf="!data">Loading</ng-container>
  <!-- ... -->
</ng-container>

or

<ng-container *let="(data$ | async) as data">
  <ng-container *ngIf="!data">Loading</ng-container>
  <!-- ... -->
</ng-container>

In other words, I want to make use of the as binding to avoid multiple subscriptions, but I don't actually want to render that container conditionally.

Is this possible? It feels like there should be an easy answer that I'm missing. :-)


On a side note, of course I know that I could just do

data$.takeUntil(this.destroy$).subscribe(data => this.data = data);

in my component class, but I'm wondering whether there's a way to avoid this and handle it in the template directly.

Ingo Bürk
  • 19,263
  • 6
  • 66
  • 100

0 Answers0