My JSON
file called employee
looks like this:
[
{
"id": "E01",
"name": "neetha",
"age": 20,
"gender": "female",
},
{
"id": "E02",
"name": "Kiran",
"age": 24,
"gender": "male",
},
{
"id": "E03",
"name": "Jhon",
"age": 28,
"gender": "male",
}
]
I have an component called list
where i am filtering this employees
with their names using custom pipes like this:
list.component.html
<div>
<mat-form-field>
<input matInput [(ngModel)]="searchTerm" placeholder="Search">
</mat-form-field>
<mat-selection-list class="list">
<mat-list-option *ngFor="let employee of employees | employeeFilter : searchTerm; let i=index">
<a mat-list-item (click)="onSelect(employee,i)"><span>{{employee.name}}</span></a>
</mat-list-option>
</mat-selection-list>
</div>
employee-filter.pipe.ts
import { PipeTransform, Pipe } from '@angular/core';
import { Employee } from '../models/employee.model';
@Pipe({
name: 'employeeFilter'
})
export class EmployeeFilterPipe implements PipeTransform {
transform(employees: Employee[], searchTerm: string): Employee[] {
if (!employees || !searchTerm) {
return employees;
}
return employees.filter(employee =>
employee.name.toLowerCase().indexOf(searchTerm.toLowerCase()) !== -1);
}
}
Now the i am filtering using the name
property, but i want to filter using age
,gender
along with name
. Using the same input field i want to filter. How can i achieve this?
Just use or operator ||
return employees.filter(employee =>
employee.name.toLowerCase().indexOf(searchTerm.toLowerCase()) !== -1)
|| employee.age.toLowerCase().indexOf(searchTerm.toLowerCase()) !== -1)
|| employee.gender.toLowerCase().indexOf(searchTerm.toLowerCase()) !== -1)
);