35

I am using Angular 2 and would like to check if a variable value is undefined using the htm *ngIf condition.

If I use <span *ngIf="!testvar">, it also covers the case when variable testvar = 0, but I would like to exclude the case when it is 0.

The following works, but those are 2 checks:

<span *ngIf="!testvar && testvarl != 0"></span>

I would like to check this case with only condition to shorten it and make it cleaner.

Is there a simple way to do this?

Alexander Abakumov
  • 13,617
  • 16
  • 88
  • 129
user1892775
  • 2,001
  • 6
  • 37
  • 58

4 Answers4

53

You can just write:

*ngIf="testvar !== undefined"
Alexander Abakumov
  • 13,617
  • 16
  • 88
  • 129
diopside
  • 2,981
  • 11
  • 23
4

And if you might be worried about null too:

*ngIf="testvar !== undefined && testvar !== null"
daxtersky
  • 410
  • 3
  • 9
2
<ng-template [ngIf]="!!foo">
  <p>Hello World</p>
</ng-template>

"Hello World" will be hidden if foo is the undefined or null or empty string and it will show Hello World if the foo is a number or boolean is true or string or array or object.

Vinod M
  • 29
  • 2
0

Despite, this is an old topic, this is a possible solution that can help others:

<span *ngIf="isValid(testvar)"></span>

isValid(str: String) {
    return typeof str !== 'undefined' && str != 0;
}
gilbriatore
  • 658
  • 7
  • 12