angularangular-ng-ifangular-template

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?


Solution

  • As discussed in this issue, this is the expected behavior. NgIf coerces the given expression into a boolean value. If the expression evaluates into a falsy value (values that are translated into false) then the content wont be rendered.

    The following are all the values that javascript currently translates to false:

    if (false)
    if (null)
    if (undefined)
    if (0)
    if (NaN)
    if ('')
    if ("")
    if (``)