[Fixed] get async result in template and use as a normal variable?

Issue

I’ve been trying to refactor some Angular code to take advantage of the async pipe and get rid of a bunch of subscriptions in my components, but it ends up looking really messy inside the template when I have to async pipe a ton of references to a Observable<Item> variable instead of assigning it once as an Item.

Is there a way to assign an observable result stream to a variable within the template and then use it as normal? For example, go from this:

    <div *ngIf="item | async">
        <p>{{ (item | async).property1 }}</p>
        <p>{{ (item | async).property2 }}</p>
        <p>{{ (item | async).property3 }}</p>
    </div>

to something like this:

    <div *ngVariableHere="(item | async) as item">
        <p>{{ item.property1 }}</p>
        <p>{{ item.property2 }}</p>
        <p>{{ item.property3 }}</p>
    </div>

Or in a case like this, is it more the ‘Angular way’ to just subscribe to the observable in the component and assign the resulting value to item?

Many thanks!

Solution

You were close in your second example, try let item instead of as item

<div *ngIf="item | async; let item">
    <p>{{ item.property1 }}</p>
    <p>{{ item.property2 }}</p>
    <p>{{ item.property3 }}</p>
</div>

STACKBLITZ

This is a stackblitz example of using ng-template and passing the object via $implicit

https://stackblitz.com/edit/ng-template-vhp6m4?file=src/app/app.component.html

Here is SO answer used to create example

What is $implicit in angular 2?

Leave a Reply

(*) Required, Your email will not be published