首页 > 解决方案 > 如何使用角度 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
   );
  }

}

但是当我在输入字段上输入时过滤不起作用?

标签: angulartypescriptpipe

解决方案


我们可以使用 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="&#61442;  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>

这将负责过滤结果列表中的数据。希望这会帮助你。


推荐阅读