How to check null or empty or undefined in Angular?
null checking is a common validation that every developer needs to know.
In this tutorial, We are going to discuss how to check a null or empty, or undefined check-in Angular.
Angular uses Typescript as a programming language, Since typescript is strongly typed so We are going to discuss multiple ways to check null
We are going to discuss multiple ways
- Checking null in Angular template HTML component
 - Checking null in the Angular typescript component
 - Angular check for Array is empty or null or undefined
 - Angular check for the object is null or undefined
 - Angular ngIf null check
 
How to check if a variable string is empty or undefined or null in Angular
This example checks a variable of type string or object checks
- Angular typescript component
 - Template HTML component
 
Typescript component, Written a function for checking null or undefined, or empty using the typeOf operator It is check for undefined values and returns true if it is null
isNameCheck(): boolean {
    if (typeof this.stringValue != 'undefined' && this.stringValue) {
      return false;
    }
    return true;
  }
Here is a complete Angular component example
import { Component, VERSION } from "@angular/core";
@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"],
})
export class AppComponent {
  stringValue = null;
  isNameCheck(): boolean {
    if (typeof this.stringValue != "undefined" && this.stringValue) {
      return false;
    }
    return true;
  }
}
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.
stringValue can be a number or string or array or object
<div *ngIf="stringValue">
  <span>stringValue is not empty</span>
</div>
<div *ngIf="!stringValue">
  <span>stringValue is empty.</span>
</div>
{{isNameCheck()}}
NgIf array is empty check-in Angular
ngIf checks an array using length and returns the length of an array.
The below code is checked below things.
- myArray is empty or not used? operator
 - if myArray is not null, It checks for the length property
 
<div *ngIf="!myArray?.length ">
  <span>Array is empty</span>
</div>
<div *ngIf="myArray?.length ">
  <span> The array is not empty </span>
</div>
Check if an object is empty in Angular
In the typescript component, We can check using the custom function which checks if there are no properties in An object.
import { Component, VERSION } from "@angular/core";
@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"],
})
export class AppComponent {
  stringValue = null;
  myArray = [];
  isObjectCheck(obj: any): boolean {
    for (var key in this) {
      if (this.hasOwnProperty(key)) return false;
    }
    return true;
  }
}
