Search code examples
angularasync-pipe

Can I unwrap an observable with the async pipe to a view variable other than with an ngIf?


I know I can use *ngIf="obs$ | async as obs" but what if I need to use the value when obs is false?

<ng-container *ngIf="obs$ | async as obs">
  observable is {{ obs | json }}
</ng-container>

https://stackblitz.com/edit/angular-zkbemb?file=src%2Fapp%2Fapp.component.html

I want that line to read observable is false instead of the block disappearing. I know I could use an else block but what I need is to unwrap a readonly$ flag to a view variable readonly and don't want to repeat my whole template in an else block. I can't think of any way that doesn't involve subscribing in the component but this is not the only occasion had have found myself wanting a way in the template to go #boolFlag = boolObs$ | async


Solution

  • Thanks to this comment on a Reddit post

    https://www.reddit.com/r/Angular2/comments/m2r39u/angular_ngif_learn_all_the_features_available_in/gqku9f9/

    <ng-container *ngIf="{ obs: obs$ | async } as data">
      observable is {{ data.obs | json }}
    </ng-container>
    

    https://stackblitz.com/edit/angular-ghxtsn?file=src%2Fapp%2Fapp.component.html