检查对象属性是否存在于对象数组中

时间:2020-08-11 07:18:51

标签: arrays angular for-loop object ngfor

如果我具有以下对象数组:

abc: [ { id: 1, name: 'fred', lastName: 'curt' }, { id: 2, name: 'bill' }, { id: 2, username: 'ted', lastName: 'zapata' } ]

是否有一种方法可以使用*ngFor来遍历HTML页面上的数组,以检查特定的lastName属性是否已经存在?

例如:

<div *ngFor="let a of abc">
  <p>{{a.name}}</p>
  <p>//if a.lastName property is not present, show some message</p>
</div>

3 个答案:

答案 0 :(得分:0)

您可以使用*ngIf== null / != null比较来进行检查。为避免将两个*ngIf与反向语句一起使用,您还可以使用ng-template关键字使我们else个。

<div *ngFor="let a of abc">
  <p>{{a.name}}</p>

  <!-- display last name if it's defined, otherwise use the #noLastName template -->
  <p *ngIf="lastName != null; else noLastName">{{ a.lastName }}</p>

  <!-- template used when no last name is defined -->
  <ng-template #noLastName><p>a.lastName property is not present</p></ng-template>
</div>

答案 1 :(得分:0)

我认为您正在寻找*ngIf指令。

代码将如下所示:

<p *ngIf="a.lastName; else noLastName"> 
   /* If true it'll show everything between the p element*/
</p>
<ng-template #noLastName>
   /*If there's no last name, everything in the ng-template noLastName will be shown but it's not necessary to have an else case.*/
</ng-template>

答案 2 :(得分:0)

您还可以执行以下操作:

<div *ngFor="let a of abc">
  <p>{{a.name}}</p>
  <p>{{a.lastName || 'Different message'}}</p>
</div>
相关问题