Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign result of async pipe to variable without *ngIf in Angular 6

Tags:

angular

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>
like image 310
DiPix Avatar asked Jul 27 '18 10:07

DiPix


People also ask

How do you use async pipe in ngIf?

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.

Why we use async pipe in angular 6?

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.

Can we use async pipe in NgFor?

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.

What is Asyncpipe?

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.


2 Answers

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.

like image 64
mcheah Avatar answered Sep 28 '22 03:09

mcheah


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

like image 44
Amit Chigadani Avatar answered Sep 28 '22 03:09

Amit Chigadani