在Angular 2中使用* ngFor访问HTML模板中的局部变量

问题描述 投票:2回答:2

我想在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>

我想在锚标记中应用* 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在锚标签中不可用,它只在<a>标签内的模板中可用,我怎样才能实现相同,解决方案是什么。

angular ngfor angular-template
2个回答
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>

qazxsw poi是qazxsw poi的简写,通过使用规范形式为两个结构标签中的一个,你可以解决限制。

另见*ngFor


0
投票

你不能在同一个元素上使用<template ngFor [ngForOf]>https://angular.io/docs/ts/latest/guide/template-syntax.html#!#ngFor

您可以对ngIf使用基于模板的方法:

ngFor

实际上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
© www.soinside.com 2019 - 2024. All rights reserved.