如何在表上启用简单的角度搜索功能并仅显示匹配的行 [英] How to implent a simple search function in angular on a Table and to show the matching rows only
本文介绍了如何在表上启用简单的角度搜索功能并仅显示匹配的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在表格上有搜索选项,我想在用户想要的页面上显示搜索到的内容.如何通过用打字稿代码编写相应的函数来实现这一点.
I have search option on Table, I want to show the searched content on the page that the user wants. How can I attain that by writing a corresponding function in code of typescript.
推荐答案
使用* ngFor在表中创建行并使用管道
Use *ngFor to create the rows in your table and use a pipe
<tr *ngFor="let item of items | filterPipe: searchToken">
添加搜索字段
<input placeholder="Type to filter" [(ngModel)]="searchToken"/>
在组件中添加变量searchToken
In the component add the variable searchToken
searchToken: string;
添加自定义管道:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'filterPipe'
})
export class FilterPipe implements PipeTransform {
transform(items: any[], searchToken: string) {
if (searchToken == null)
searchToken = "";
searchToken = searchToken.toLowerCase();
return items.filter(elem => elem.name.toLowerCase().indexOf(searchToken) > -1);
}
}
最后不要忘记将管道放入ngModule的声明中:
Finally don't forget to put the pipe into the declarations in ngModule:
declarations: [ App, FilterPipe ]
这篇关于如何在表上启用简单的角度搜索功能并仅显示匹配的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文