2016-07-05 86 views
1

我在我的網頁中的按鈕中顯示信息。按鈕顯示列表及其字段中的多個對象(例如,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) –

回答

2

管道是一個很好的解決方案,但如果你願意,你可以使用* 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> 

3

這是你管可能是什麼樣子:

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,並採取您在