Search bar in order to find word in page


#1

Hello,
I make an application with some pages where there is articles in it.
And I would like to create a search bar to find words in these pages.

At the moment I have my search bar in the toolbar but I do not see how to continue at all.
I don’t understand how it works

Can you give me some help?
Thank you


#2

This is what i have done for search bar filter.

in you .html file with searchbar

<ion-searchbar class="grey-bg" placeholder="Search more Chat & Prople" [color]="white" [(ngModel)] = "searchTerm" (ngModelChange) = "search()"></ion-searchbar>
<ion-list>

      <ion-item class="ionItemStyle" *ngFor="let a of showArray" (click)="done(a)">
        <h3 class="theme-color">{{a}}</h3>
      </ion-item>

  </ion-list>

i have defined search function whenever user search something

And in .ts file results get filtered, It is working demo.


@Component({
....
})
export class ChatPage {
   arr:any;
   showArray:any;
   public searchTerm : any;

   constructor(public navCtrl: NavController, public navParams: NavParams,private alertCtrl: AlertController) {
    this.searchTerm = '';
    this.arr = [
      'Natasha Romanoff',
      'Tony Stark',
      'Black widow',
      'Hawk Eye',
      'Thor',
      'The Hulk'
    ];
    this.showArray = this.arr;
  }

  search(): void {
    let term = this.searchTerm;

      this.showArray = this.arr.filter((tag)=> {
        tag = tag.toLowerCase();
          return tag.indexOf(term.toLowerCase()) >= 0;
      });

  }

#3

I have achieved WhatsApp like search feature, thanks to Mark.js and Scroll-into-view.

HTML part -

<ion-header id="">
    <ion-toolbar class="search-bar" no-border-top>
        <form (ngSubmit)="showCurrentMark('next')" class="search-form">
            <ion-searchbar #searchInput ion-input name="searchField"
                [(ngModel)]="searchField.content"
                showCancelButton="true"
                cancelButtonText="Close"
                (ionInput)="searchString()"
                (ionCancel)="hideSearchBar()">
            </ion-searchbar>
        </form>
        <ion-buttons end>
            <button ion-button clear (click)="showCurrentMark('prev')">
                <ion-icon name="ios-arrow-up"></ion-icon>
            </button>
            <button ion-button clear (click)="showCurrentMark('next')">
                <ion-icon name="ios-arrow-down"></ion-icon>
            </button>
        </ion-buttons>
    </ion-toolbar>
</ion-header>

TS part -

import * as Mark from 'mark.js'; // For search highlighting
import * as scrollElmIntoView from 'scroll-into-view';

export class HomePage {
  // Instance for Mark for higlighting search along with marked count
  markInstance: any; // Instance/scope of search
  markResults:any = []; // Total number marked results
  currMarkIndx = -1; // Index of in view marked search result

  searchString(){
    // Search entered string from search bar
    // Clear previous marked searches if any
    this.clearMarkedMatches();

    // Create variable for target(s) container
    var responseArr = $('#target-elements');
    var searchStr = this.searchField.content.trim(); // Current entered string

    // Create Mark instance (using JavaScript object array instead of jQuery object array)
    this.markInstance = new Mark(responseArr.toArray());
    // Supply the string to search with options
    this.markInstance.mark(searchStr);

    // Find array of marked elements
    this.markResults = responseArr.find('mark');
    this.currMarkIndx = -1; // Reset the index counter
  }
  showCurrentMark(direction){
    // Update index to highlight current mark
    if(this.markResults.length){
      if(direction == 'next'){
        if(this.currMarkIndx == -1){
          this.currMarkIndx = 0;
        }
        else{
          this.currMarkIndx == this.markResults.length - 1 ? this.currMarkIndx = 0 : this.currMarkIndx++;
        }
      }
      else if(direction == 'prev'){
        if(this.currMarkIndx == -1){
          this.currMarkIndx = this.markResults.length - 1;
        }
        else{
          this.currMarkIndx == 0 ? this.currMarkIndx = this.markResults.length - 1 : this.currMarkIndx--;
        }
      }

      this.scrollToSearched();
    }
    else{
      this.presentToast('No result found.');
    }
  }
  scrollToSearched(){
    // Scroll and highlight mark
    if(this.markResults.length){
      var position,
          currentMark = this.markResults.eq(this.currMarkIndx);

      // Remove "current" class from all elements
      this.markResults.removeClass('current');

      if(currentMark.length){
        currentMark.addClass('current');
        // Scroll to currently higligted search
        scrollElmIntoView(currentMark[0], { time: 250 });
      }
    }
    else{
      this.presentToast('No result found.');
    }
  }
  clearMarkedMatches(){
    // Clear all marked searches
    return new Promise((resolve, reject)=>{
      if(this.markInstance)
        this.markInstance.unmark();
      resolve();
    })
  }
}

#4

Looks good… but what is this target-element? Are you using jQuery to select them?


#5

Ok got it working when added jQuery (npm install jquery). For those who have the same question #target-ement would be the container element that holds the text to look into.
Thanks @sujit77!