Filtering an array in angular2

前端 未结 2 455
醉酒成梦
醉酒成梦 2020-11-30 06:31

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 geare

相关标签:
2条回答
  • 2020-11-30 07:16

    I have a similar scenario in one of my samples

    <input "(keyup)="navigate($event)" />
    
    <div *ngFor="#row of visibleRows"></div>    
    
    ......
    
    navigate($event){
            this.model.navigate($event.keyCode);
            this.visibleRows = this.getVisibleRows();
    }
    
    getVisibleRows(){
        return this.model.rows.filter((row) => row.rowIndex >= this.model.start && row.rowIndex < this.model.end);
    }
    

    My approach is to recalculate the array on some qualifying event. In my case it's keyup. It may seem convenient to bind to a function or filter, but it's recommended to bind to the array directly instead. This is because the change tracking will get confused since the function/filter will return a new array instance every time change tracking is triggered - regardless of what triggered it.

    Here is the full source: https://github.com/thelgevold/angular-2-samples/tree/master/components/spreadsheet

    I also have a demo: http://www.syntaxsuccess.com/angular-2-samples/#/demo/spreadsheet

    0 讨论(0)
  • 2020-11-30 07:23

    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

    0 讨论(0)
提交回复
热议问题