Reputation: 982
How can I make a general search into a table using pipes in Angular? I have this working snippet, but the value of i
is only 0
, and I don't know why (and because of that, it will only search for name
column only, if I type cc
it won't find anything).
How can I modify the code in order to obtain what I want? Thank you for your time!
filter.pipe.ts
transform(value: any, input: string) {
if (!value) {
return [];
}
if (!input) {
return value;
}
var valuesArr = []
if (input) {
input = input.toLowerCase();
return value.filter(function (el: any) {
valuesArr = Object.keys(el).map(key => el[key]);
for (var i in valuesArr) {
return valuesArr != null && valuesArr[i] != null && valuesArr[i] != undefined && valuesArr[i].toLowerCase().indexOf(input) > -1;
}
})
}
return value;
}
app.html
<input type="text" [(ngModel)]="toSearch" (click)="onClick(toSearch)">
<table>
<thead>
<tr>
<th>Name</th>
<th>Surname</th>
<th>Group</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let user of users | filter : toSearch">
<td>{{ user.name }}</td>
<td>{{ user.surname }}</td>
<td>{{ user.group }}</td>
<tr>
</tbody>
</table>
app.ts
toSearch
users = [
{name: "john", surname: "john1", group: null},
{name: "mike", surname: "", group: 'bb'},
{name: "anne", surname: "anne1", group: ''},
{name: "dan", surname: "dan1", group: 'cc'},
{name: "ben", surname: "", group: 'a'},
]
onClick(toSearch) {
this.toSearch = toSearch
}
Upvotes: 3
Views: 1011
Reputation: 9638
Using ES6 operators I suggest also :
transform(value: any[], input: string) {
if (!value) {
return [];
}
if (!input) {
return value;
}
var valuesArr = []
if (input) {
console.log(input)
input = input.toLowerCase();
return value.filter( (el: any) => {
valuesArr = Object.keys(el).map(key => el[key]);
return valuesArr.some((elm)=> {
if (JSON.stringify(elm).includes(input)) {
return elm;
}
return null;
})
})
}
return value;
}
Upvotes: 1
Reputation: 6527
Simple just check when your match is true only then send it through
import { Pipe, PipeTransform, Injectable } from '@angular/core';
@Pipe({
name: 'filter',
})
@Injectable()
export class CheckBoxPipe implements PipeTransform {
transform(value: any, input: string) {
if (!value) {
return [];
}
if (!input) {
return value;
}
var values = []
if (input) {
input = input.toLowerCase();
return value.filter(function (el: any) {
values = Object.keys(el).map(key => el[key]);
let result = false;
for (var i in values) {
result = values != null && values[i] != null && values[i] != undefined && values[i].toLowerCase().indexOf(input) > -1;
if(result){
return true
}
}
return false;
})
}
return value;
}
}
Upvotes: 4