[angular] Check if Variable is Empty - Angular 2

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?

This question is related to angular

The answer is


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


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
       }
    } 

}

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


Angular 4 empty data if else

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

if( myVariable ) 
{ 
    //mayVariable is not : 
    //null 
    //undefined 
    //NaN 
    //empty string ("") 
    //0 
    //false 
}

user:Array[]=[1,2,3];
if(this.user.length)
{
    console.log("user has contents");
}
else{
    console.log("user is empty");
}