Value of Observable is not displayed when it is 0 (Zero)

Viewed 799

Using Angular 8, I have the following:

<ng-container *ngIf="(count$ | async) as count; else loader">{{count}}</ng-container>
<ng-template #loader>
    loading
</ng-template>

The variable count$ is an Observable<number> ...

When count$ value is 1, 2, etc the value is correctly displayed.

But when the count$ value is 0 it shows only loading.

Any idea why?

2 Answers

Since you want to test the value of the observable in a condition and also display that value in the view, you can use two nested ng-container tags. The first one gets the count value (using a technique explained in this article), and the second one uses the value in the condition and in the view. This structure allows to reuse the value without creating multiple subscriptions to the same observable.

<ng-container *ngIf="{ count: count$ | async } as data">
  <ng-container *ngIf="data.count === 0 || data.count > 0; else loader">
    {{data.count}}
  </ng-container>
</ng-container>
<ng-template #loader>
  loading
</ng-template>

See this stackblitz for a demo.

Because it is falsy value: Boolean(0) === false. Nothing special ;)

UPD:

.ts

this.count$;

constructor() {
  this.count$ = interval(2000).pipe(map(i => `${i}`));
}

.html

<ng-container *ngIf="count$ | async as count; else loader">
  {{ count }}
</ng-container>
<ng-template #loader>
  loading
</ng-template>

Related