角度过滤表 [英] 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>
现在假设我想过滤我的数组.如果我有固定的行数,我可以选择在 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屋!