Search code examples
angularrxjsobservable

How to handle boolean observables with the async pipe in Angular


I have the following code:

public obs$: Observable<boolean>
<div *ngIf="(obs$ | async) === true || (obs$ | async) === false">
  {{ (obs$ | async) ? 'yes' : 'no' }}
</div>

It works as intended, but the if looks a little verbose.

The problem is that I cannot simply do <div *ngIf="(obs$ | async)">. If I try that, it will work in the case when the observable did not emit a value yet or if the value is true, but it will not work if the value is false, because the if will evaluate to false and the div is not displayed.

I assume the same issue applies if a falsy value is returned, such as an empty string or 0.

Is there a better, easier way of doing that?


Solution

  • You can do (obs$ | async) !== null