如果我具有以下对象数组:
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>
答案 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>