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

3

*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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.