1
votes

I have this totally legit data source:

public data = [
  { Field1: 1, Field2: 'One' },
  { Field1: 2, Field2: 'Two' },
  { Field1: 3, Field2: 'Three' },
  { Field1: 4, Field2: 'Four' }
];

I'm displaying it in a table like this:

<table>
  <thead>
    <th>Field1</th>
    <th>Field2</th>
  </thead>
  <tbody>
    <tr *ngFor="let item of data">
      <td>{{item.Field1}}</td>
      <td>{{item.Field2}}</td>
    </tr>
  </tbody>
</table>

Now suppose I want to filter my array. If I had a fixed number of rows, I could elect to show/not show an item using *ngIf on the tr elements, but Angular doesn't allow two structural directives on one element.

I'm aware I can simply filter the source array using Array.filter, but that makes a copy, which may be an issue if my array is much bigger.

I thought of nesting the row in something (div, maybe?), but I'm not certain that is valid HTML.

So what is the correct way to dynamically filter data using Angular 2?

2
You can write your own Pipe to show filtered result on view..Pankaj Parkar
ng-container or template might help youyurzui
@PankajParkar The Angular docs warns against this due to performance concerns.Cobus Kruger

2 Answers

1
votes

You can use something like this:

<table>
  <thead>
    <th>Field1</th>
    <th>Field2</th>
  </thead>
  <tbody>
    <ng-container *ngFor="let item of data">
      <tr *ngIf="someCondition">
         <td>{{item.Field1}}</td>
         <td>{{item.Field2}}</td>
      </tr>
    </ng-container>
  </tbody>
</table>
0
votes

Possible ways:

  • using a Pipe -> you don't need a copy
  • using a filtered array

Angular prefers the way of filtering that data into another "copy".

https://angular.io/docs/ts/latest/guide/pipes.html#!#no-filterpipe-or-orderbypipe-

Reasons are performance and minifiying..

So its up to you. :)

If you need any examples, give me a comment and i'll give you a plunker.