Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
655 views
in Technique[技术] by (71.8m points)

typescript - Filtering an array in angular2

I am looking into how to filter an array of data in Angular2.

I looked into using a custom pipe, but I feel this is not what I am looking for, as it seems more geared towards simple presentation transformations rather then filtering large sets of data.

The array is set out as follows:

getLogs(): Array<Logs> {
        return [
            { id: '1', plate: 'plate1', time: 20 },
            { id: '1', plate: 'plate2', time: 30 },
            { id: '1', plate: 'plate3', time: 30 },
            { id: '2', plate: 'plate4', time: 30 },
            { id: '2', plate: 'plate5', time: 30 },
            { id: '2', plate: 'plate6', time: 30 }
        ];
    }

I want to filter this by id. So when I enter "1" into a search bar, it updates to display the corresponding values.

If there is a method on how to do this, I would love to know!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There is no way to do that using a default pipe. Here is the list of supported pipes by default: https://github.com/angular/angular/blob/master/modules/angular2/src/common/pipes/common_pipes.ts.

That said you can easily add a pipe for such use case:

import {Injectable, Pipe} from 'angular2/core';

@Pipe({
    name: 'myfilter'
})
@Injectable()
export class MyFilterPipe implements PipeTransform {
    transform(items: any[], args: any[]): any {
        return items.filter(item => item.id.indexOf(args[0]) !== -1);
    }
}

And use it:

import { MyFilterPipe } from './filter-pipe';
(...)

@Component({
  selector: 'my-component',
  pipes: [ MyFilterPipe ],
  template: `
    <ul>
      <li *ngFor="#element of (elements | myfilter:'123')">(...)</li>
    </ul>
  `
})

Hope it helps you, Thierry


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...