HTML check variable undefined with ngIf excluding case when value is 0
Asked Answered
U

4

37

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?

Universalize answered 22/8, 2017 at 22:2 Comment(0)
C
56

You can just write:

*ngIf="testvar !== undefined"
Collaborative answered 22/8, 2017 at 22:6 Comment(0)
G
4

And if you might be worried about null too:

*ngIf="testvar !== undefined && testvar !== null"
Gris answered 9/4, 2020 at 13:48 Comment(3)
This can be shortened to *ngIf="testvar != undefined"Pulmonary
I believe this could also be *ngIf="!!testvar"Hullo
no because that will also kill the 0, because 0 is falsy and that is the whole point of the question.Fireboard
D
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.

Defalcate answered 12/1, 2021 at 9:33 Comment(1)
This will also be false if "foo" is number 0. And [ngIf] should be *ngIfEsta
D
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;
}
Defilade answered 11/6, 2021 at 0:39 Comment(1)
You don't want to use functions in your template like that, for performanceCuss

© 2022 - 2024 — McMap. All rights reserved.