Saturday, 2 March 2019

Ionic 4 Search filter using pipe

       Here I am going to explain how to create ionic list search  using Pipe

Step 1

        Create a ionic empty project

        Create class Contact
               ionic generate class Contact

        Create pipe Search
               ionic generate pipe Search 

              And copy below code to search pipe

                     transform(names: any[], terms: string): any[]
                     {
                        if(!names) return [];
                        if(!terms) return names;
                         terms= terms.toLowerCase();
                          return names.filter( it => {
                          return it.name.toLowerCase().includes(terms);
                        });
                    }
                  
         Add Searchpipe in home,module.ts declarations and not in app.module

                     declarations: [HomePage,SearchPipe]
     
  Step 2 

         Create search list using Contact class

              export class Contact
              {
                      id:number;
                      name:string;
              }



        Add below code in homepage

              import { SearchPipe } from '../search.pipe';
              import { Contact } from '../contact';

              export class HomePage {

                contacts: Contact[] = [
                     { id: 1, name: 'Dhina'},
                     { id: 2, name: 'Vignesh'},
                     { id: 3, name: 'Venkatesh'},
                     { id: 4, name: 'Dhina'},
                     { id: 5, name: 'Arun'},
                     { id: 6, name: 'Vimal'},];

                       constructor() {}
                       names:SearchPipe;
               }

       Add below css in css file

                .circle-pic
               {
                  width:50px;
                  height:50px;
                  -webkit-border-radius: 50%;
                  border-radius: 50%;
                 }

    Add below footer and content in html file

     <ion-content padding>
     <ion-grid>
        <ion-row text-center>
          <ion-col  col-4 col-md-3 col-xl-2 *ngFor="let contact of contacts | search:names"                                        style="white- space: nowrap">
       
              <img src="any image url"/>
              <div>
                <ion-label style="font-size: 10px">{{contact.name}}</ion-label>
                <br>
              </div>
          </ion-col>
        </ion-row>
      </ion-grid></ion-content>
    <ion-footer >
    <ion-toolbar>
        <ion-searchbar color="light" placeholder="Contact Search" [(ngModel)]="contact"></ion-                              searchbar>
      </ion-toolbar>
   </ion-footer>


       

  

1 comment:

  1. This is a helpful guide for implementing search functionality in an Ionic application.

    ReplyDelete