如何在Angular中检查null 或 empty 或 undefined?

1,250 阅读2分钟

空值检查是每个开发者都需要知道的一种常见验证。

在本教程中,我们将讨论如何在Angular中检查空或空或未定义的检查。

Angular使用Typescript作为编程语言,由于Typescript是强类型的,所以我们将讨论检查空的多种方法。

我们将讨论多种方法

  • 在Angular模板html组件中检查null
  • 在Angular typescript组件中检查null
  • Angular检查数组是否为空或空或未定义
  • Angular检查对象是否为空或未定义
  • Angular ngIf null检查

如何在Angular中检查变量字符串是否为空或未定义或为空?

这个例子检查一个字符串或对象类型的变量。

  • Angular typecript组件
  • 模板html组件

Typescript组件,使用typeOf操作符编写了一个检查null或undefined或empty的函数,它是检查未定义的值,如果是null则返回true。

isNameCheck(): boolean {
    if (typeof this.stringValue != 'undefined' && this.stringValue) {
      return false;
    }
    return true;
  }

这里是完整的Angular组件例子

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

在模板html组件中。

我们可以使用ngIf指令来检查空值或未定义值。

在这个例子中,如果stringValue是空的、空的或未定义的,它就会打印出空信息

stringValue可以是数字、字符串、数组或对象。

<div *ngIf="stringValue">
  <span>stringValue is not empty</span>
</div>

<div *ngIf="!stringValue">
  <span>stringValue is empty.</span>
</div>
{{isNameCheck()}}

Angular中的NgIf数组空检查

ngIf使用长度检查一个数组并返回数组的长度。

下面的代码是检查以下内容

  • myArray是否为空,使用?
  • 如果myArray不是空的,它就会检查长度属性。
<div *ngIf="!myArray?.length ">
  <span>Array is empty</span>
</div>
<div *ngIf="myArray?.length ">
  <span>
    Array is not empty
  </span>
</div>

在Angular中检查一个对象是否为空

在typescript组件中,我们可以使用自定义函数来检查一个对象中是否有任何属性。

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