简体   繁体   中英

Angular search filter

I'm trying to implement search filter in angular 2 for that I Have implement below code

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import{Pipe,PipeTransform} from '@angular/core';
import { AppComponent } from './app.component';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';

@NgModule({
  declarations: [
    AppComponent,   
  ],
  imports: [
    BrowserModule,
    FormsModule,
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

app.component.ts

import { Component, Injectable } from '@angular/core';
import {Pipe, PipeTransform} from '@angular/core';

@Pipe({
    name: 'searchFilter'
})
export class SearchFilter implements PipeTransform {
    transform(items: any[], criteria: any): any {

        return items.filter(item =>{
           for (let key in item ) {
             if((""+item[key]).toLocaleLowerCase().includes(criteria.toLocaleLowerCase())){
                return true;
             }
           }
           return false;
        });
    }
}

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements P {
  title = 'app';
    users:any[]=[
           {sid:124,sname:"Angular"},
           {sid:125,sname:"Ionic"},
           {sid:126,sname:"mobile"}]
  }

app.component.html

<div class="container">
<h4>Creating Custom Pipes</h4>
 <input #search  (keyup)="0">
 <div *ngFor="let user of (users | searchFilter: search.value )">
   {{user.sname}}
  </div>  
</div>

But in the browser console log it is showing below error

Uncaught Error: Template parse errors:The pipe 'searchFilter' could not be found (".

I'm not able to figured out what is the error. Could any one please help to achieve this

Add SearchFilter in your module under declarations

NgModule({
  declarations: [
    AppComponent,  
    SearchFilter  
  ],
  imports: [
    BrowserModule,
    FormsModule,
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM