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

标签 angular ngfor angular-template

我正在尝试在 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/

相关文章:

以编程方式路由回页面时,Angular 不会调用 ngOnInit

angular - Webpack 和 TypeScript - 包括 Moment.js 插件

angular - *ngFor 如何使用索引将数组中的每个项目绑定(bind)到 ngModel

angular - 如何使用 ngFor 使卡片在 Angular 6 中保持在一行?

Angular 2 - ng-bootstrap 如何为他们的 NgbRadio 指令提供 NgbRadioGroup 和 NgbButtonLabel?

angular - Manifest.json 未复制到 dist

angular - 使用 Angular2 禁用文本框的剪切、复制和粘贴功能的指令

angular - 在 ngFor 中加载最后一项后调用指令

javascript - ng-include 具有混合值硬编码和范围内的变量

angularjs - 如何从 Grails 插件提供的 JS 文件中指向 AngularJS 模板?