1

I am looking to filter multiple columns from one pipe and I cant seem to get it right. I have managed to get it to work with searching a single column but not multiple columns. I have tried implementing this stackoverflow answer but I get an error of

ERROR TypeError: Cannot convert undefined or null to object.

Here is my code for a single column:

@Pipe({
    name: 'filter'
})

@Injectable()
export class FilterPipe implements PipeTransform {
    transform(items: any[], field: string, value: string): any[] {
        if (!items) {
            return [];
        }
        if (!field || !value) {
            return items;
        }
        return items.filter(singleItem => singleItem[field].toLowerCase().includes(value.toLowerCase()));
}
}

Html
 <tr *ngFor="let user of users | orderby: {property: column, direction: direction} | filter : 'FirstName' : searchString; let i = index"> 
    <td>{{user.Salutation.Description}}</td>
    <td>{{user.FirstName}}</td>
    <td>{{user.Surname}}</td>
    <td>{{user.Region.Description === "None" ? "-" : 
        user.Region.Description</td>
<td>{{user.Institution === null ? "-" : user.Institution}}</td>
<td>{{user.PrimaryResearchField.Description === "None" ? "-" : user.PrimaryResearchField.Description}}</td>
<td>{{user.OrcidID === null ? "-" : user.OrcidID}}</td>
</tr>                     

Any help would be gratefully received.

Thanks

Axel
  • 3,331
  • 11
  • 35
  • 58
dd65tn
  • 23
  • 6

1 Answers1

-1

Hi I have implemented it this way in My co

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


@Pipe({
    name: 'filter',
    pure: false
})

export class FilterPipe implements PipeTransform {
    transform(items: any[], field : any, value : string): any[] {  
        if (!items) return [];   
        if(typeof field == 'string'){ 
            let rtItems:any = items;
            try{
                rtItems = items.filter(it => it[field].toLowerCase().indexOf(value.toLowerCase()) > -1 );
            }finally{
                return rtItems;
            }
        }else{ 
            let rtItems:any = items;
            try{
                rtItems = items.filter(it => {
                    for(let f of field){
                        if(it[f].toLowerCase().indexOf(value.toLowerCase()) > -1){
                            return true;
                        }
                    }
                });
            }finally{
                return rtItems;
            }
        }


    }
}

and in html you can use it like this for Multiple

*ngFor="let booking of bookings | filter:['name','number','date']:searchKey"

or this way for single

*ngFor="let booking of bookings | filter:'name':searchKey"

please let me know if it works or you find any issues

tanveer ahmad dar
  • 3,312
  • 1
  • 27
  • 29