iamsimonsmale
iamsimonsmale

Reputation: 541

ngIf Async Pipe as value with only null check

I have an observable that I would like to create a variable with in the ngIf as well as only return false if the value is null (the observable returns a number)

I need to explicitly check for null as my observable can return 0 as a value which triggers the else block.

I have tried the following

*ngIf="(observable$ | async) as obs; obs !== null; esle #elseTemplate"
*ngIf="((observable$ | async) as obs) !== null; esle #elseTemplate"
*ngIf="(observable$ | async) !== null; $implicit = obs; else #elseTemplate"
// this returns the boolean 

My current solution which doesn't seem very elegant is

*ngIf="(observable$ | async) !== null; esle #elseTemplate"
{{ observable$ | async }}

I am using Angular 10.

Upvotes: 5

Views: 5084

Answers (2)

Mathew Berg
Mathew Berg

Reputation: 28750

Usually when I deal with observables in the template like this, I find it far easier to create a single vm$ observable that's built from other observables in the component like this (note, eventually combineLatest will support dictionaries which will mean you won't have to do the map):

vm$ = combineLatest([
    this.observable$,
    this.observable2$
])
.pipe(
    map(([observable, observable2]) => ({
        observable,
        observable2
    }))
);

Then in your dom, you do an ngIf on the vm$ and you can compare the output of your observable directly.

<ng-container *ngIf="vm$ | async as vm">
    <ng-container *ngIf="vm.observable !== null; else #elseTemplate">
    
    </ng-container>
    ...
</ng-container>

EDIT For when combineLatest supports a dictionary the vm$ creation becomes simpler:

vm$ = combineLatest({
    observable: this.observable$,
    observable2: this.observable2$
})

Upvotes: 5

MoxxiManagarm
MoxxiManagarm

Reputation: 9124

Another approach I can recommend is the usage of the ngx observe directive from Nils Melhorn https://github.com/nilsmehlhorn/ngx-observe

With this directive you are allowed to define templates for next, loading and even error. The next template also is triggered if a falsy value like your zero is emitted.

*ngxObserve="observable$; let obs; before loadingTemplate; error errorTemplate"

Upvotes: 0

Related Questions