Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NgIf and zero: Why is the template not being rendered?

I have the following observable on and Angular component:

count$: Observable<number>;

this.count$ = this.getCount();

By using the following I get the value 0 (Zero);

this.count$.subscribe(x => console.log(x));

On the template I have:

<a routerLink="/dash" *ngIf="(count$ | async)">
  <ng-container *ngIf="count$ | async as count">
    Count: {{count}}
  </ng-container>
</a> 

If count$ is 1 I get Count: 1 but if count$ is 0 the content Count: 0 is not even rendered.

Any idea why?

like image 462
Miguel Moura Avatar asked Sep 02 '25 16:09

Miguel Moura


1 Answers

In case anyone is looking for a workaround, this so stupid but it works:

   <ng-container *ngIf="{ len: count$ | async } as ctx">
      <ng-container *ngIf="ctx.len !== null"        
          {{ ctx.len }} 
       </ng-container>
   </ng-container>

Explanation:

  1. Capture count as len inside of an object called ctx
  2. Because *ngIf is now looking at an object, instead of the value, it will evaluate as truthy and render the ng-container
  3. Now we check whether we got an actual value or not with ctx.len !== null
  4. We can access the value using ctx.len
like image 123
Patrick Avatar answered Sep 04 '25 05:09

Patrick