Prakash Prakash - 2 years ago 291
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>

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>

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

Answer Source

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

*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!#ngFor

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download