angularrxjsangular10rxjs-observablesasync-pipe

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.


Solution

  • 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$
    })