【问题标题】:Check if object property exists within a array of objects检查对象属性是否存在于对象数组中
【发布时间】:2020-11-30 19:59:30
【问题描述】:

如果我有以下对象数组:

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>

【问题讨论】:

  • &lt;p *ngIf="..."&gt; 呢?

标签: arrays angular for-loop object ngfor


【解决方案1】:

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

<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="a.lastName,因为如果字符串为空、null 或未定义,则返回 false,如果有任何值,则返回 true。可以通过将! 添加为*ngIf="!a.lastName 来反转
  • 对。 “属性已经存在”意味着一个空检查 - 所以 '' 可能是一个有效值。
【解决方案2】:

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

【讨论】:

    【解决方案3】:

    你也可以这样做:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-16
      • 1970-01-01
      • 1970-01-01
      • 2012-07-27
      • 2021-12-27
      相关资源
      最近更新 更多