Prakash Prakash - 7 months ago 126
HTML Question

Accessing local variable in html template using *ngFor in angularjs 2

I am trying to use ngFor in angularjs2, 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.

Answer

*ngFor and *ngIf on the same tag is not supported.

Use instead:

  <template ngFor #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

Comments