如何过滤(带管道)列表?

时间:2017-10-19 13:23:30

标签: angular typescript pipe

我有一个过滤管道:

@Pipe({
name: 'filter'
})
export class FilterPipe implements PipeTransform {
transform(items: Array<any>, filter: { [key: string]: any }): Array<any> {
    return items.filter(item => {
        let notMatchingField = Object.keys(filter)
            .find(key => item[key] !== filter[key]);
        return !notMatchingField; // true if matches all fields
    });
}


}

我在anotherpage.html中过滤了我的列表:

<tr *ngFor="let item of _FilteredList | filter:peopleFilter" >

在anotherpage.ts中我检测到peopleFilter的上下文:

this.peopleFilter = { NAME: 'Gülcan' };

所以我运行它,我的所有对象的名字都是'Gülcan'在我的表中。但我在另一页写道:console.log(this._FilteredList)我看到该列表中的所有项目。反正只有那些过滤过的物品?

2 个答案:

答案 0 :(得分:1)

过滤器不会更改源数组。它会生成另一个数组,然后在模板中呈现。目前无法访问它,但另一方面,我认为这不是必要的。如果您需要在代码中使用过滤数组,只需将其放在那里并将其呈现在模板中而不是原始模板中。

所以,你想要的是这样的:

<强> app.component.ts

import {Component} from '@angular/core';
import {AppFilter} from './filter.pipe';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent {
    items: any[] = [];
    filteredItems: any[] = [];
    private _filterId: string;
    get filterId(): string {
        return this._filterId;
    }
    set filterId(val: string) {
        this._filterId = val;
        this.filteredItems = this.filter.transform(this.items, {id: val});
    }
    constructor(private filter: AppFilter) {
        this.items = [
            {
                id: '1',
                text: 'item 1'
            },
            {
                id: '2',
                text: 'item 2'
            }
        ];
        this.filterId = '1';
    }
}

<强> app.component.html

<div>
    <input type="text" [(ngModel)]="filterId" />
    <div *ngFor="let item of filteredItems">{{item.text}}</div>
</div>

<强> app.module.ts

import {BrowserModule} from '@angular/platform-browser';
import {NgModule} from '@angular/core';

import {AppComponent} from './app.component';
import {FormsModule, ReactiveFormsModule} from '@angular/forms';
import {AppFilter} from './filter.pipe';

@NgModule({
    declarations: [
        AppComponent,
        AppFilter
    ],
    imports: [
        BrowserModule,
        FormsModule,
        ReactiveFormsModule
    ],
    providers: [AppFilter], // <--- !!! it must be provided by some component or module
    bootstrap: [AppComponent]
})
export class AppModule {
}

<强> filter.pipe.ts

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

@Pipe({
    name: 'filter'
})
export class AppFilter implements PipeTransform {
    transform(value: any, filter: {[key: string]: any}): any {
        if (!value || !filter) {
            return value;
        }
        return value.filter(item => {
            return !Object.keys(filter).find(key => filter[key] && (item[key] !== filter[key]));
        });
    }
}

答案 1 :(得分:0)

尝试使用此代码进行过滤。它对我有用:

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

@Pipe({
    name: 'filterPipe'
})
export class FilterPipe implements PipeTransform {
    transform(data: any[], keys: string[], filter: string) {
        if (!filter || !keys || keys.length <= 0) {
            return data;
        } else {
            return data.filter((elem) => {
                var matched = false;
                for (let key of keys) {
                    matched = matched || elem[key].toLocaleLowerCase().indexOf(filter.toLocaleLowerCase()) !== -1
                    if (matched) {
                        return true;
                    }
                }
                return matched;
            });
        }
    }
}

<强>更新 HTML:

<tr *ngFor="let item of (_FilteredList | filterPipe:peopleFilter)">