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?
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.
You can simply use typeof. It will check undefined, null, 0 and "" also.
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.
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.
if( myVariable )
{
//mayVariable is not :
//null
//undefined
//NaN
//empty string ("")
//0
//false
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With