显然,Angular 2将像在Angular1中一样使用管道而不是过滤器,并结合ng-for来过滤结果,尽管实现看起来仍然很模糊,没有明确的文档。

也就是说,我想要达到的目标可以从以下角度来看待

<div *ng-for="#item of itemsList" *ng-if="conditon(item)"></div>

如何实现这样使用管道?


当前回答

我知道这是一个老问题,但是,我认为提供另一种解决方案可能会有所帮助。

相当于AngularJS的这个

<div *ng-for="#item of itemsList" *ng-if="conditon(item)"></div>

在Angular 2+中,你不能在同一个元素上使用*ngFor和*ngIf,所以它会如下所示:

<div *ngFor="let item of itemsList">
     <div *ngIf="conditon(item)">
     </div>
</div>

如果你不能作为内部容器使用ng-container代替。 ng-container在你想有条件地在你的应用程序中添加一组元素(例如使用*ngIf="foo")但不想用另一个元素包装它们时很有用。

其他回答

我使用了一个动态过滤管道

源数据:

items = [{foo: 'hello world'}, {foo: 'lorem ipsum'}, {foo: 'foo bar'}];

在模板中,你可以在任意对象attr中动态设置过滤器:

<li *ngFor="let item of items | filter:{foo:'bar'}">

管:

  import { Pipe, PipeTransform } from '@angular/core';

  @Pipe({
    name: 'filter',
  })
  export class FilterPipe implements PipeTransform {
    transform(items: any[], filter: Record<string, any>): any {
      if (!items || !filter) {
        return items;
      }

      const key = Object.keys(filter)[0];
      const value = filter[key];

      return items.filter((e) => e[key].indexOf(value) !== -1);
    }
  }

不要忘记在app.module.ts声明中注册管道

我根据这里和其他地方的答案创建了一个活塞。

此外,我必须添加一个<input>的@Input, @ViewChild和ElementRef,并创建和订阅()到它的一个可观察对象。

Angular2搜索过滤器:PLUNKR(更新:plunker不再工作)

管子是最好的方法。但低于1也可以。

<div *ng-for="#item of itemsList">
  <ng-container *ng-if="conditon(item)">
    // my code
  </ng-container>
</div>

在谷歌搜索之后,我发现了ng2-search-filter。In将获取您的对象并对所有对象属性应用搜索项以查找匹配项。

第一步是在组件中使用@Pipe创建Filter。ts文件:

your.component.ts

import { Component, Pipe, PipeTransform, Injectable } from '@angular/core';
import { Person} from "yourPath";

@Pipe({
  name: 'searchfilter'
})
@Injectable()
export class SearchFilterPipe implements PipeTransform {
  transform(items: Person[], value: string): any[] {
    if (!items || !value) {
      return items;
    }
    console.log("your search token = "+value);
    return items.filter(e => e.firstName.toLowerCase().includes(value.toLocaleLowerCase()));
  }
}
@Component({
  ....
    persons;

    ngOnInit() {
         //inicial persons arrays
    }
})

和Person对象的数据结构:

person.ts

export class Person{
    constructor(
        public firstName: string,
        public lastName: string
    ) { }
}

在你的html文件视图中:

your.component.html

    <input class="form-control" placeholder="Search" id="search" type="text" [(ngModel)]="searchText"/>
    <table class="table table-striped table-hover">
      <colgroup>
        <col span="1" style="width: 50%;">
        <col span="1" style="width: 50%;">
      </colgroup>
      <thead>
        <tr>
          <th>First name</th>
          <th>Last name</th>
        </tr>
      </thead>
      <tbody>
        <tr *ngFor="let person of persons | searchfilter:searchText">
          <td>{{person.firstName}}</td>
          <td>{{person.lastName}}</td>
        </tr>
      </tbody>
    </table>