Using 'as' like with an *ngIf

Viewed 781

When using an *ngIf, you can do something like *ngIf = (value$ | async).property as prop and then use prop throughout your code without needing to repeat the long (value$ | async).property each time. However, this only works if (value$ | async).property is a truthy value - and not if it is zero for instance.

My question is - how can I still reap the benefits of as but still have the element show if the value is falsy? Or better yet, is there a way to use as outside of an *ngIf or the like?

2 Answers

PMO1948, "the trick" is create an object, credits to Yury Katkov

<div *ngIf="{values: (value$ | async)} as prop">
    ..inside use, e.g.
    {{prop.values?.property}}
    <div *ngIf="!prop.values">
        the observable return nothing
    </div>
</div>

If "value$ |async" return nothing, the *ngIf exist anyway

Sample Demo

Below is another trick you can implement using ||

<div *ngIf="(value$ | async) || {}  as prop">
    ..inside use, e.g.
    {{prop.property}}
    <div *ngIf="!prop.property">
        the observable return nothing
    </div>
</div>

See Demo Here

Update

Came across ngrxLet Structural Directive and this looks like an interesting solution

The *ngrxLet directive serves a convenient way of binding observables to a view context (a dom element scope) The *ngrxLet directive is provided through the ReactiveComponentModule.`

import { NgModule } from '@angular/core';
import { ReactiveComponentModule } from '@ngrx/component';

@NgModule({
  imports: [
    // other imports
    ReactiveComponentModule
  ]
})
export class MyFeatureModule {}

With the above you can use it

<div  *ngrxLet="value$ as prop">
    ..inside use, e.g.
    {{prop.property}}
    <div *ngIf="!prop.property">
        the observable return nothing
    </div>
</div>
Related