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
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,
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
}
}
}
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");
}
Source: Stackoverflow.com