0

I have created a pipe in my angular 5 project, which will takes the input from html and filter array and will return filtered array. But currently I am passing the property name("firstName") from HTML file. Now i want that, it should filter from properties "firstName" and "lastName" both. Please tell me what should i change to do the same ???

search-filter.pipe.ts

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

@Pipe({
    name: 'searchFilter'
})
export class SearchFilter implements PipeTransform {
    transform(data: any, search?: string, propertyName?: string): any {
        if (search === undefined) {
            return data;
        } else {
            return data.filter(obj => obj[propertyName].toLowerCase().includes(search.toLowerCase()));
        }
    }
}

user.component.html

<div class="row" *ngFor="let data of datas| searchFilter: search: 'firstName'}">
   {{data.lastName}}, {{data.firstName}}
</div>

sample-data.ts

 datas: [
{ firstName: 'vipin', company: 'abc', lastName: 'sharma' },
{ firstName: 'kevin', company: 'abc2', lastName: 'xyz' },
{ firstName: 'Leos', company: 'abc3', lastName: 'abc' },
]
2
  • Pass search text like 'firstName|lastName' & split that in pipe then search appropriate Commented Jun 4, 2018 at 7:59
  • Could you please write the code of directive. Commented Jun 4, 2018 at 8:33

3 Answers 3

1

I got my answer and its working fine :

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

@Pipe({
    name: 'searchFilter'
})
export class SearchFilter implements PipeTransform {
    transform(data: any, search?: string, propertyName?: string, propertyName2?: string): any {
        if (search === undefined) {
            return data;
        } else {
            let filteredData = data.filter(obj => obj[propertyName].toLowerCase().includes(search.toLowerCase()));
            if (propertyName2) {
                filteredData = filteredData.concat(data.filter(obj => obj[propertyName2].toLowerCase().includes(search.toLowerCase())));
            }
            return filteredData;
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

What you can do is concat the properties you want to search on:

this.items.map((item) => {
  return {...item, searchTerms: item.firstname + item.lastname;
});

<li *ngFor="let item of items | searchFilter:search:'searchTerms'>{{item.name}}</li>

Comments

0

Can you try like this

 this.data.filter((element: datatype) =>element.firstName && element.lastName)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.