General search pipe Angular6

Tenzolinho

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
  }
joyBlanks

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;
  }
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related