I have an array of objects which i am trying to filter with the search value
component ts
filterArray = [
{'id': 1, 'name': 'ABC', 'type': 'IT'},
{'id': 2, 'name': 'XYZ', 'type': 'Tech'},
{'id': 3, 'name': 'LMN', 'type': 'IT'},
{'id': 4, 'name': 'PQR', 'type': 'Software'},
{'id': 5, 'name': 'JKL', 'type': 'hardware'},
{'id': 5, 'name': 'EFG', 'type': 'hardware'}
];
@ViewChildren('filterRef') filtedItems;
custom pipe
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'filter'
})
export class FilterPipe implements PipeTransform {
transform(value: any, args?: any): any {
if (value && args) {
const arr = value.filter((e: any) => e.type.toLowerCase() === args.toLowerCase());
if (arr.length > 0) {
return arr;
} else {
return [];
}
}
return value;
}
}
HTML
Search : <input type="text" name="search" [(ngModel)]="search">
<ul *ngFor="let item of filterArray | filter: search as result" #filterRef>
<li>{{item.name}}</li>
</ul>
Filtered Length : {{filtedItems?.length}}
I am trying to get the length of the filtered resultant array am getting below error
can anyone help me to fix this?..
If filtering should be done with the pipe, the only possibility is to do that in a surrounding context:
<ng-container *ngIf="filterArray | filter: search as result">
<ul *ngFor="let item of result" #filterRef>
<li>{{item.name}}</li>
</ul>
<p>{{result?.length}}</p>
</ng-container>