Handling Falsy Values Emitted from Observables in Angular
In the last year or so, I’ve been fully embracing reactive programming in my Angular apps. That means goodbye subscribe
and hello async
pipe! It’s been great, but there have been a couple times where the async
pipe, in conjunction with the *ngIf
structural directive, have not worked as I needed them to. The issue arises when the emitted value from the observable is falsy. When the emitted value is falsy, the *ngIf
doesn’t output the content on the screen. I understand why that happens, but many times the falsy value is a valid result and should be displayed. In this post, we’ll cover an easy way to still use the async
pipe and *ngIf
while still outputting falsy values.
The Issue Explained
Recently, I was working on an application at work where we needed to output the emitted value of an observable. The value was a number with zero being a valid result. We also wanted to display a loading spinner while waiting on data from the API. We did that with the *ngIf
structural directive and the else
option that goes along with it. Here’s a brief sample of what that looked like:
<div
*ngIf=”observableValue$ | async as value; else backupLoader”>
{{ value }}
</div><ng-template #backupLoader>
<app-loader></app-loader>
</ng-template>