angular - 如何使用角度 2 中的管道过滤列表
问题描述
你能告诉我如何使用角度 2 中的管道过滤列表吗
https://stackblitz.com/edit/angular-qvtqeu?file=src%2Fapp%2Fapp.component.html
我试过这样
<ul class="user-list | filterlist:userenter">
<li *ngFor="let user of users" class="user-list__item">
筛选
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'filterlist'
})
export class FilterlistPipe implements PipeTransform {
transform(value: any, args?: any): any {
return value.filter(
item => item.first_name.toLowerCase().indexOf(args.toLowerCase()) > -1
);
}
}
但是当我在输入字段上输入时过滤不起作用?
解决方案
我们可以使用 ng2-search-filter npm。
有关更多详细信息,您可以查看此演示:
演示链接
app.module.ts
我们必须安装ng2-search-filter包,然后我们必须在 app.module.ts 中导入它,如下所示。
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
// search module
import { Ng2SearchPipeModule } from 'ng2-search-filter';
import { AppComponent } from './app.component';
@NgModule({
imports: [ BrowserModule, FormsModule, Ng2SearchPipeModule ],
declarations: [ AppComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
title = 'Angular Search Using ng2-search-filter';
searchText;
heroes = [
{ id: 11, name: 'Mr. Nice', country: 'India' },
{ id: 12, name: 'Narco' , country: 'USA'},
{ id: 13, name: 'Bombasto' , country: 'UK'},
{ id: 14, name: 'Celeritas' , country: 'Canada'},
{ id: 15, name: 'Magneta' , country: 'Russia'},
{ id: 16, name: 'RubberMan' , country: 'China'},
{ id: 17, name: 'Dynama' , country: 'Germany'},
{ id: 18, name: 'Dr IQ' , country: 'Hong Kong'},
{ id: 19, name: 'Magma' , country: 'South Africa'},
{ id: 20, name: 'Tornado' , country: 'Sri Lanka'}
];
}
app.component.html
| filter:searchText将发挥过滤的魔力。
*ngFor="let hero of heroes | filter:searchText"
因此,让我们将它添加到我们实际迭代列表的 HTML 中的 for 循环中。
<div class="container text-center">
<h1>{{title}}</h1>
</div>
<div class="container">
<div class="row">
<div class="search-hero">
<input class="form-control" type="text" name="search" [(ngModel)]="searchText" autocomplete="off" placeholder=" Start searching for a hero by id or name or country">
</div>
<table class="table table-striped">
<thead>
<tr>
<th>Id</th>
<th>Hero Name</th>
<th>Country</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let hero of heroes | filter:searchText">
<td>{{hero.id}}</td>
<td>{{hero.name}}</td>
<td>{{hero.country}}</td>
</tr>
</tbody>
</table>
</div>
</div>
这将负责过滤结果列表中的数据。希望这会帮助你。
推荐阅读
- elasticsearch - 为什么 IndexOrDocValuesQuery 需要这么长时间?
- medium.com - 我想抓取 medium.com 网站上的所有帖子
- python-3.x - 从函数更改列表中的布尔值状态?
- c++ - OPENCV:查找线方向/角度
- machine-learning - 回归问题,使用 L1、L2 和 R2 时如何解释基线结果
- types - 输入函数式编程 (OCaml)
- npm - 即使在 npm init 之后,npm 也会全局安装包
- python-3.x - numpy 数组列表而不是一个热向量
- html - css动画无法在导航栏中实现
- mysql - 初始化mysql centos 6时遇到问题