在ngFor循环中检查空值

问题描述:

我在我的网页中的按钮中显示信息。按钮显示列表及其字段中的多个对象(例如,object.name,object.age等)。在某些情况下,其中一个字段为空。我该如何去检查一个值是否为空?如果它为空,我想打印“未知” - 至此它不打印任何内容。在ngFor循环中检查空值

这里是我的ngFor环路(在我的情况,环境有时是空):

<button *ngFor="let object of objects; let i = index" type="button" style="text-align:left; margin-right: 10px; margin-bottom: 10px" class="btn btn-primary" 
     Name: {{object.name}} <br /> Locations: {{object.date}} <br /> Environments: {{object.environment}} 
</button> 

我知道我可以手动设置的环境,“未知”,因为它是一个字符串值,但我想知道是否有办法通过html来做到这一点。

+3

编码框架,充分利用这听起来像一个良好的使用对于[管道](https://angular.io/docs/ts/latest/guide/pipes.html) –

管道是一个很好的解决方案,但如果你愿意,你可以使用* ngIf直接用HTML:

<button *ngFor="let object of objects; let i = index" type="button" style="text-align:left; margin-right: 10px; margin-bottom: 10px" class="btn btn-primary" 
    Name: <span *ngIf="object.name">{{object.name}}</span> <span *ngIf="!object.name">Unknown</span> 

这是你管可能是什么样子:

import { Pipe, PipeTransform } from '@angular/core'; 

@Pipe({name: 'unknown'}) 
export class Unknown implements PipeTransform { 
    transform(value: any): any { 
    return value ? value : 'Unknown' 
    } 
} 

在您的组件内部,您需要包含管道:

@Component({ 
... 
pipes: [Unknown] // this is whatever you named your exported class 

然后在你的HTML你会

... 
<br /> Environments: {{object.environment | unknown}} //this is whatever name you put in the @Pipe decorator 

个人而言,我喜欢管更好,因为它留下了更清洁更可读的HTML,并采取您在