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

问题描述

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

abc: [ { id: 1,name: 'fred',lastName: 'curt' },{ id: 2,name: 'bill' },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>

解决方法

您可以使用*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>
,

我认为您正在寻找*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>
,

您还可以执行以下操作:

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

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...