2016-04-21 70 views
2

我想在angularjs2使用ngFor訪問局部變量在HTML模板,下面使用* ngFor在Angular2

<a *ngFor="#facet of facet_data" class="collection-item" (click)="setToSearchBarWithFilter(facet.category)"> 
    {{facet.category}}<span class="badge">{{facet.count}}</span> 
</a> 

我想申請* ngIf在錨標記,只顯示那些具有標籤示例代碼facet.count> 0,這樣的事情:

<a *ngFor="#facet of facet_data" class="collection-item" (click)="setToSearchBarWithFilter(facet.category)" *ngIf="facet.count > 0"> 
    {{facet.category}}<span class="badge">{{facet.count}}</span> 
</a> 

但方面是不具備的錨標記,它只是在<a>標籤內的模板可用,我怎麼能達到同樣的,該如何解決。

回答

3

*ngFor*ngIf在同一個標​​籤不支持。

使用,而不是:

<ng-container *ngFor="let facet of facet_data"> 
    <a class="collection-item" (click)="setToSearchBarWithFilter(facet.category)" *ngIf="facet.count > 0"> 
    {{facet.category}}<span class="badge">{{facet.count}}</span> 
    </a> 
    </ng-container> 

<ng-container>是不加蓋到DOM的輔助元素。

仍然支持,但不推薦,因爲混亂的語法:

<template ngFor let-facet [ngForOf]="facet_data"> 
    <a class="collection-item" (click)="setToSearchBarWithFilter(facet.category)" *ngIf="facet.count > 0"> 
    {{facet.category}}<span class="badge">{{facet.count}}</span> 
    </a> 
    </template> 

*ngFor<template ngFor [ngForOf]>速記使用規範形式兩個可以解決結構的標籤之一侷限性。

又見https://angular.io/docs/ts/latest/guide/template-syntax.html#!#ngFor

0

您不能在同一元素上使用ngIfngFor

你可以使用基於模板的方法爲ngFor

<template ngFor #facet [ngForOf]="facet_data"> 
    <a class="collection-item" 
     (click)="setToSearchBarWithFilter(facet.category)"> 
    {{facet.category}}<span class="badge">{{facet.count}}</span> 
    </a> 
</template> 

其實ngFor是一個結構性的指令,並使用*ngFor是使用template標籤的方法語法快捷方式。

有關詳細信息,你可以看看在這部分鏈接「*和」: