用 *ngIf 检查是否有数组 (Angular 4)

check with *ngIf, if there is an array or not (Angular 4)

我正在使用 *ngFor 遍历 json 文件。在遍历数据时,我想检查每个人是否没有颜色数组。我使用 *ngIf 执行此操作。

JSON

[
  {
    "name": "Peter",
    "colors": [
      {
        "color": "blue"
      },
      {
        "color": "yellow"
      }
    ]
  },
  {
    "name": "Maria"
  }
  // has no colors array
]

HTML

<div *ngFor="let person of persons">
     <div *ngIf=" what comes here?? ">
        <p>{{person.name}} has no colors</p>
     </div>          
</div>

如果一个人没有颜色数组,我该如何检查?

非常简单:

 <div *ngIf="!person.colors">
     <p>{{person.name}} has no colors</p>
 </div> 

试试这个

<div *ngFor="let person of persons">
  <div *ngIf="person.colors && person.colors.length">

有了文字,就给了

If the array exists and has at least one element in it

相反的是

  <div *ngIf="!person.colors || !person.colors.length">

您可以使用 Elvis operator

来缩短
<div *ngIf="!person.colors?.length">