Home > database >  implement search function (filter) in angular [Part 2]
implement search function (filter) in angular [Part 2]

Time:12-04

I tried to import 'CommonModule' but it gives me the same error message. If, on the other hand, I try to write of between car and cars, it underlines the word filter as an error and displays me as an error:

no pipe found with name 'filter'. I need to implement a simple search function

<div *ngFor="let car in cars | filter : searchText">

I expected typing this statement the search method worked properly

CodePudding user response:

Please find the attached code snippet with simple search function with given array :

app.component.html :

<div >
  <h1>{{title}}</h1>
</div>
<div >
  <div >
    <div >
      <input  type="text" name="search" [(ngModel)]="searchText" autocomplete="off" placeholder="&#61442;  Start searching for a hero by id or name or country">
    </div>
    <table >
      <thead>
      <tr>
        <th>Id</th>
        <th>Hero Name</th>
        <th>Country</th>
      </tr>
      </thead>
      <tbody>
      <tr *ngFor="let hero of heroes | filter:searchText">
        <td>{{hero.id}}</td>
        <td>{{hero.name}}</td>
        <td>{{hero.country}}</td>
      </tr>
      </tbody>
    </table>
  </div>
</div>

app.component.ts :

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  title = 'Angular Search Using ng2-search-filter';
  searchText;
  heroes = [
    { id: 11, name: 'Mr. Nice', country: 'India' },
    { id: 12, name: 'Narco' , country: 'USA'},
    { id: 13, name: 'Bombasto' , country: 'UK'},
    { id: 14, name: 'Celeritas' , country: 'Canada' },
    { id: 15, name: 'Magneta' , country: 'Russia'},
    { id: 16, name: 'RubberMan' , country: 'China'},
    { id: 17, name: 'Dynama' , country: 'Germany'},
    { id: 18, name: 'Dr IQ' , country: 'Hong Kong'},
    { id: 19, name: 'Magma' , country: 'South Africa'},
    { id: 20, name: 'Tornado' , country: 'Sri Lanka'}
  ];
}

Please find the working stackblitz example using ng2-search-filter here

  • Related