如果我有以下对象数组:
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>
您可以使用*ngIf
和== null / != null
比较进行检查。为了避免使用两个具有相反语句的*ngIf
,您也可以使用else
关键字来创建ng-template
。
<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>