角度过滤表 [英] Angular filtered table

查看:91
本文介绍了角度过滤表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个完全合法的数据源:

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>

现在假设我要过滤我的数组.如果行数固定,则可以选择在tr元素上使用*ngIf显示/不显示项目,但是Angular不允许在一个元素上使用两个结构指令.

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.

我知道我可以简单地使用Array.filter过滤源数组,但这会产生一个副本,如果我的数组更大,这可能是个问题.

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.

我考虑过将行嵌套在某些内容中(也许是div?),但我不确定这是有效的HTML.

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

那么使用Angular 2动态过滤数据的正确方法是什么?

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

推荐答案

您可以使用以下内容:

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

这篇关于角度过滤表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆