Search code examples
angulartemplatesangularjs-filter

Angular filtered table


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?


Solution

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