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>
Use the async pipe with ngIfThe condition (obsValue | async) becomes true , when the observable returns a value. Until then the elseBlock is shown, which we use to display the loading indicator. In the example, it displays the message Observable is loading.
The async pipe subscribes to an Observable or Promise and returns the latest value it has emitted. When a new value is emitted, the async pipe marks the component to be checked for changes. When the component gets destroyed, the async pipe unsubscribes automatically to avoid potential memory leaks.
NgFor has a not-so-obvious feature that lets us will help us deal with asynchronous operations - the async pipe. The async pipe takes care of subscribing/unsubscribing to Observable streams for us.
Angular's async pipe is a tool to resolve the value of a subscribable in the template. A subscribable can be an Observable , an EventEmitter , or a Promise . The pipe listens for promises to resolve and observables and event emitters to emit values. Let's take a look at how we can profit from using the async pipe.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With