Tuesday, March 28, 2017

Simple search using pipe in angular 2

In this article I will be explaining about how to implement a simple search using pipe concept. I have explained in my previous articles how to do a simple search or filtering using angular 1. If you want to compare both implementation you can refer Angular js 1 basic search and filter data with example.

OK, let’s start with our Angular 2 simple search implementation using pipe.

I will share the app module code as well to avoid any confusion

App module code

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import {FilterPipe} from './pipes'

import { AppComponent } from './app.component';

  declarations: [
  imports: [
  providers: [],
  bootstrap: [AppComponent]
export class AppModule { }

"FilterPipe" is nothing but our pipe name and './pipe' is the typscript file path which has pipe code.

Let us check our component code

App component

import { Component } from '@angular/core';
import {FilterPipe} from './pipes'

  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
export class AppComponent {
    this.title = "Angular 2 simple search";
        this.names = ['Prashobh','Abraham','Anil','Sam','Natasha','Marry','Zian','karan']

Here you can see a simple array which contains some names. The template url is nothing but our html.

Template [ templateUrl: './app.component.html']

  <h3> {{title}}</h3>
  <input type="text" [(ngModel)]="queryString" id="search" placeholder="Search to type">

    <li *ngFor="let n of names | FilterPipe: queryString">

Now create a pipe and name as "FilterPipe". Check below code for pipe.


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

    name: 'FilterPipe',
export class FilterPipe implements PipeTransform {
    transform(value: any, input: string) {
        if (input) {
            input = input.toLowerCase();
            return value.filter(function (el: any) {
                return el.toLowerCase().indexOf(input) > -1;
        return value;

We are done. Run the application and start typing on text box you can see filtered result.

You can go to our GitHub page and download all the code as well. Download code from GitHub page.

Related Post

1. ng-if in angular 2

2. Show and hide in angular 2.

3. Get selected values on click and show in the UI - Angular js 2