Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use async pipe in ngFor on Observable of Observables (Angular)

I have variable defined like this: myVar: Observable<Observable<MyObject>[]>.

I am using Angular4 feature to enumerate with async pipe

*ngFor="let obsMyObject of (myVar | async)"

now I have Observable of MyObject, but I need just MyObject. I could write something like that:

<div *ngFor="let obsMyObject of (myVar | async)">
    <div *ngIf="let obsMyObject | async; let MyObject"></div>
</div>

but I can not do this in inner div, because I am setting flex order (which doesn't have any effect on inner div) property so I need something like this:

<div *ngFor="let obsMyObject of (myVar | async); let MyObject = (obsMyObject | async)"
    [style.order]="MyObject.order">
</div>

I just had one idea how to do this, and I tried this:

<div *ngFor="let obsMyObject of (myVar | async); let MyObject = obsMyObject)">
    {{MyObject}}
</div>

but MyObject is undefined, so there is no way let MyObject = (obsMyObject | async) would work.

like image 393
Makla Avatar asked Dec 09 '17 14:12

Makla


People also ask

Can async pipe be used 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.

Can I use async pipe in component?

The async pipe in angular will subscribe 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.

Is Observable subscribe async?

An observable produces values over time. An array is created as a static set of values. In a sense, observables are asynchronous where arrays are synchronous. In the following examples, → implies asynchronous value delivery.

What kind of data can be used with async pipe?

With AsyncPipe we can use promises and observables directly in our template, without having to store the result on an intermediate property or variable.


1 Answers

I think you want to use an ng-container and an ngIf to subscribe and create reference to the observable. Then from within the ng-container you can reference this new variable as if it was a plain object.

<ng-container *ngIf="myVar$| async as myVar">
   <div *ngFor="let obsMyObject of myVar">
    {{obsMyObject }}
   </div>
</ng-container>

The use of myVar and object is really confusing. Here's a better example:

Property in component declared as:

users$: Observable<User[]> 

And the template:

<ng-container *ngIf="users$ | async as users">
   <div *ngFor="let user of users">
     {{ user.name }}
   </div>
</ng-container>
like image 61
cgatian Avatar answered Oct 13 '22 03:10

cgatian