How to apply filters to *ngFor?

前端 未结 23 1287
無奈伤痛
無奈伤痛 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条回答
  •  梦毁少年i
    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

        
        
    First name Last name
    {{person.firstName}} {{person.lastName}}

提交回复
热议问题