Accessing local variable in HTML template using *ngFor in Angular 2

I am trying to use ngFor in Angular 2, sample code below

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

I want to apply *ngIf in the anchor tag to show only those tags which has facet.count > 0, something like this:

<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>

But facet is not available in the anchor tag, its only available in the template inside the <a> tag, how can I achieve the same, what is the solution.

2
Leave a Reply

avatar
2 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Jason Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Jason
Guest

*ngFor and *ngIf on the same tag is not supported. Use instead: <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> is a helper element that is not stamped to the DOM. Still supported but not recommended because of the confusing syntax: <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 is the short hand for <template ngFor [ngForOf]> by using the canonical form for one of both structural tags you can work around the limitation. See also https://angular.io/docs/ts/latest/guide/template-syntax.html#!#ngFor

Jason
Guest

You can’t use ngIf and ngFor on the same element.

You could use the template-based approach for 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>

In fact ngFor is a structural directive and using *ngFor is a syntax shortcut for the approach using the template tag.

For more details, you could have a look at this link in the section “* and “: