我正在尝试在 Angular 2 中使用 ngFor,示例代码如下
<a *ngFor="#facet of facet_data" class="collection-item" (click)="setToSearchBarWithFilter(facet.category)">
{{facet.category}}<span class="badge">{{facet.count}}</span>
</a>
我想在 anchor 标记中应用 *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>
但是facet在 anchor 标记中不可用,它仅在<a>
内的模板中可用。标签,我怎样才能达到同样的效果,解决方案是什么。
最佳答案
*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
关于angular - 在 Angular 2 中使用 *ngFor 访问 HTML 模板中的局部变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36762228/