20

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?

karns
  • 5,391
  • 8
  • 35
  • 57

7 Answers7

25

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.

Mitch Talmadge
  • 4,638
  • 3
  • 26
  • 44
Vish
  • 832
  • 7
  • 21
5
if( myVariable ) 
{ 
    //mayVariable is not : 
    //null 
    //undefined 
    //NaN 
    //empty string ("") 
    //0 
    //false 
}
Yoav Schniederman
  • 5,253
  • 3
  • 28
  • 32
4

You can play here with different types and check the output,

Demo

export class ParentCmp {
  myVar:stirng="micronyks";
  myVal:any;
  myArray:Array[]=[1,2,3];
  myArr:Array[];

    constructor() {
      if(this.myVar){
         console.log('has value')     // answer
      }
      else{
        console.log('no value');
      }

      if(this.myVal){
         console.log('has value') 
      }
      else{
        console.log('no value');      //answer
      }


       if(this.myArray){
          console.log('has value')    //answer
       }
       else{
          console.log('no value');
       }

       if(this.myArr){
             console.log('has value')
       }
       else{
             console.log('no value');  //answer
       }
    } 

}
micronyks
  • 54,797
  • 15
  • 112
  • 146
2
user:Array[]=[1,2,3];
if(this.user.length)
{
    console.log("user has contents");
}
else{
    console.log("user is empty");
}
Kofi Sammie
  • 3,237
  • 1
  • 17
  • 17
1

Ar you looking for that:

isEmptyObject(obj) {
  return (obj && (Object.keys(obj).length === 0));
}

(found here)

or that :

function isEmpty(obj) {
    for(var key in obj) {
        if(obj.hasOwnProperty(key))
            return false;
    }
    return true;
}

found here

user1767316
  • 3,276
  • 3
  • 37
  • 46
0

It depends if you know the given variable Type. If you expect it to be an Object than you could check if myVar is an empty Object like this:

 public isEmpty(myVar): boolean {
     return (myVar && (Object.keys(myVar).length === 0));
 }

Otherwise: if (!myVar) {}, should do the job

Uliana Pavelko
  • 2,824
  • 28
  • 32
-1

Angular 4 empty data if else

if(this.data == 0)
{
alert("Null data");
}
else
{
//some logic
}