UIAPPDEVELOPER
UIAPPDEVELOPER

Reputation: 649

How to add search fllter in a table in angular 7

I have a table whose data is coming from loop also I need to add search functionality into it,I have tried to create custom pipe but it was not working,Can anyone please help me on it,Here is the code below

app.component.html

<input type="text" placeholder="search..">
<table class="table border">
    <thead>
    <tr>
      <ng-container *ngFor="let column of columns; let i = index">
        <th>{{ column }}</th>
      </ng-container>
    </tr>
    </thead>
    <tbody>
      <tr *ngFor="let row of groups;let i = index" >
          <td>{{row.name}}</td>
          <td>{{row.items}}</td>

      </tr>
    </tbody>
  </table>

app.component.ts

import { Component,ViewChild, ElementRef } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent  {
columns = ["name", "Items"];

  groups=[
     {
       "id": 1,
       "name": "pencils",
       "items": "red pencil"
     },
     {
       "id": 2,
       "name": "rubbers",
       "items": "big rubber"
     },
      {
      "id": 3,
       "name": "rubbers1",
       "items": "big rubber1"
     },
  ];
}

Upvotes: 0

Views: 38

Answers (1)

ahmeticat
ahmeticat

Reputation: 1939

Firstly, update your html input and table array like that

<input type="text" placeholder="search.." (input)="onChange($event.target.value)" >
<table class="table border">
    <thead>
    <tr>
      <ng-container *ngFor="let column of columns; let i = index">
        <th>{{ column }}</th>
      </ng-container>
    </tr>
    </thead>
    <tbody>
      <tr *ngFor="let row of viewedGroups;let i = index" >
          <td>{{row.name}}</td>
          <td>{{row.items}}</td>

      </tr>
    </tbody>
  </table>

After that in your ts

viewedGroups = [];
...
ngOnInit(){
  this.viewedGroups = this.groups;
}

onChange(value){
   this.viewedGroups = this.groups.filter(a=>a.name.toLowerCase().search(value.toLowerCase())>-1 || a.items.toLowerCase().search(value.toLowerCase())>-1)
}

Please examine example

Upvotes: 1

Related Questions