0

How do I filter elements when using ng-for?

<tr>
    <td *ng-for="#col of columns" ><a (click)="sort(col.name)">{{col.title}}</a></td>
</tr>

I don't want to create a element when col.visible is false

How do I do this in Angular2?

Sangwin Gawande
  • 7,658
  • 8
  • 48
  • 66
Murali
  • 3,412
  • 5
  • 36
  • 34
  • 1
    I think what you need is what was called in Angular 1 a filter, which is now called a pipe, see this answer http://stackoverflow.com/questions/31214924/angular-2-only-one-directive-per-element. check this on pipes https://angular.io/docs/js/latest/api/pipes/ and how to create a custom one -> https://angular.io/docs/js/latest/api/change_detection/Pipe-class.html – Angular University Jul 13 '15 at 13:39

4 Answers4

1

You can use a pipe to filter the data so that only a subset is used by *ngFor like explained in

How to apply filters to *ngFor

or you can use *ngIf with *ngFor, but they are not allowed on the same element. How to use them together anyway is explained in *ngIf and *ngFor on same element causing error

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
0

Use ngIf directive. col.visible = true means only the td is added otherwise it won't be added in the tr.

The ngIf directive removes or recreates a portion of the DOM tree based on an {expression}. If the expression assigned to ngIf evaluates to a false value then the element is removed from the DOM, otherwise a clone of the element is reinserted into the DOM.

<tr>
    <td ng-if="col.visible" ng-for="#col of columns" ><a ng-click="sort(col.name)">{{col.title}}</a></td>
</tr>
Sudharsan S
  • 15,336
  • 3
  • 31
  • 49
0

In this case the simplest thing to do is to ensure that your columns array is only populated with col objects where col.visible === true.

Doing that in the controller class will fix this problem without any markup filters or other framework specific dependencies.

TGH
  • 38,769
  • 12
  • 102
  • 135
0

Angular2 syntax has changed a bit. For the release, the syntax for a *ngIf is:

<div class="row pre-scrollable" *ngIf="count > 0">
    <div *ngFor="let image of results">
        {{image.title}}
    </div>
</div>

The results is an array of some objects that have a title and count is the number of items in that array.

In this case, the div is used to have a scrollable list of results and if there are no results, to hide the scrollbar.

Herb F
  • 135
  • 8