Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if Variable is Empty - Angular 2

Tags:

How can one check if a variable is empty in Angular 2? I know that there are native ways such as

if (myVar === null) {do stuff}

but I am looking for something like Angular 1 had such as

if (angular.isEmpty(variable)) { do stuff }.

Q How do check if variable is empty using Angular 2?

like image 543
karns Avatar asked Apr 01 '16 15:04

karns


People also ask

How do you check if a variable is empty or not in angular?

How to check if a variable string is empty or undefine or null in Angular. In template HTML component: We can use the ngIf directive to check empty null or undefined. In this example, if stringValue is empty or null, or undefined, It prints the empty message.

How do I check if a string is null or empty in typescript?

You can simply use typeof. It will check undefined, null, 0 and "" also.

Is AngularJS undefined?

The angular. isUndefined() function in AngularJS is used to determine the value inside isUndefined function is undefined or not. It returns true if the reference is undefined otherwise returns false. Return Value: It returns true if the value passed is undefined else returns false.


2 Answers

Lets say we have a variable called x, as below:

var x;

following statement is valid,

x = 10;
x = "a";
x = 0;
x = undefined;
x = null;

1. Number:

x = 10;
if(x){
//True
}

and for x = undefined or x = 0 (be careful here)

if(x){
 //False
}

2. String x = null , x = undefined or x = ""

if(x){
  //False
}

3 Boolean x = false and x = undefined,

if(x){
  //False
}

By keeping above in mind we can easily check, whether variable is empty, null, 0 or undefined in Angular js. Angular js doest provide separate API to check variable values emptiness.

like image 102
Vish Avatar answered Oct 06 '22 16:10

Vish


if( myVariable ) 
{ 
    //mayVariable is not : 
    //null 
    //undefined 
    //NaN 
    //empty string ("") 
    //0 
    //false 
}
like image 39
Yoav Schniederman Avatar answered Oct 06 '22 15:10

Yoav Schniederman