How to apply filters to *ngFor?

前端 未结 23 1278
無奈伤痛
無奈伤痛 2020-11-22 03:44

Apparently, Angular 2 will use pipes instead of filters as in Angular1 in conjunction with ng-for to filter results, although the implementation still seems to be vague, wit

相关标签:
23条回答
  • 2020-11-22 04:11

    Simplified way (Used only on small arrays because of performance issues. In large arrays you have to make the filter manually via code):

    See: https://angular.io/guide/pipes#appendix-no-filterpipe-or-orderbypipe

    @Pipe({
        name: 'filter'
    })
    @Injectable()
    export class FilterPipe implements PipeTransform {
        transform(items: any[], field : string, value : string): any[] {  
          if (!items) return [];
          if (!value || value.length == 0) return items;
          return items.filter(it => 
          it[field].toLowerCase().indexOf(value.toLowerCase()) !=-1);
        }
    }
    

    Usage:

    <li *ngFor="let it of its | filter : 'name' : 'value or variable'">{{it}}</li>
    

    If you use a variable as a second argument, don't use quotes.

    0 讨论(0)
  • 2020-11-22 04:11

    This is what I implemented without using pipe.

    component.html

    <div *ngFor="let item of filter(itemsList)">
    

    component.ts

    @Component({
    ....
    })
    export class YourComponent {
      filter(itemList: yourItemType[]): yourItemType[] {
        let result: yourItemType[] = [];
        //your filter logic here
        ...
        ...
        return result;
      }
    }
    
    0 讨论(0)
  • 2020-11-22 04:11

    I know its an old question, however, I thought it might be helpful to offer another solution.

    equivalent of AngularJS of this

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

    in Angular 2+ you cant use *ngFor and *ngIf on a same element, so it will be following:

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

    and if you can not use as internal container use ng-container instead. ng-container is useful when you want to conditionally append a group of elements (ie using *ngIf="foo") in your application but don't want to wrap them with another element.

    0 讨论(0)
  • 2020-11-22 04:11

    The first step you create Filter using @Pipe in your component.ts file:

    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
        }
    })
    

    And data structure of Person object:

    person.ts

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

    In your view in html file:

    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>
    
    0 讨论(0)
  • 2020-11-22 04:12

    Ideally you should create angualr 2 pipe for that. But you can do this trick.

    <ng-container *ngFor="item in itemsList">
        <div*ngIf="conditon(item)">{{item}}</div>
    </ng-container>
    
    0 讨论(0)
提交回复
热议问题