Browser find (Ctrl-F) function with next/prev occurrence functionality

Hi, I am looking for ways to create a search bar which has function like browser’s find, but my target platform is Android platform.

(For this I am not using any ionic UI components)
For which I have successfully created a search bar with a text input using

<input type="text" placeholder="Search">

and the matched letters are highlighted by assigning a background-color style to the matched cases with DOM Sanitizer:


However, I would like to add a Next/Prev function that would allow jumping to the location of next occurrence of such pattern.
Just like what is offered in Chrome with Ctrl + F

So far the answers I have found are all using jQuery, so I am curious if there is any Angular-Ionic solution to this.

So, since you are able to detect and highlight them, you could put all matches in an array and use a pointer to point to previous or next location. By pointer I mean instance variables of a Component.

I actually did the detection and highlight in a pipe typescript file
The pipe replaces the matched parts with
<span style="background-color:yellow">${searchInput}</span>
…Which I feel clueless of how to store the matches as data, after all they are just strings, but with comparison

Ok, how does the match occur? Is it a string comparison or a regex?

Regex to identify the pattern of search input (case insensitive), and do a
string.replace(regex, <element that highlights the text>)

I came up with a way, though kinda hard-coded my way out of this. I am open for better suggestions though!

This is my approach to achieve the goal:
First in the pipe TS file I added a class to highlighted parts, like this:

...replace(regex,(match) =>
<span style="background-color:yellow" class="logMsg">${searchInput}</span>)

Then inside the search box I put an event listener, in HTML:
<input type="text" ... (keyup)="getMatch($event)"

in corresponding TS:

/* async otherwise this.elements is always undefined */
async getMatch(event) {
// elements declared as type HTMLCollectionOf<any>
    this.elements = document.getElementsByClassName('logMsg');
// to prevent error for undefined searchInput and undefined this.elements
    if (this.searchInput && this.elements[0]) {
// immediately jump to the first occurrence
        this.elements[0].scrollIntoView({block: 'end'});

Similarly for next and previous occurrence selection just add event listener like:

next() {
   if (this.searchInput && this.elements[index+1]) {
        this.elements[index].scrollIntoView({block: 'end'});

… and so on
scrollIntoView scrolls my outer container instead of inner container, that kinda makes it distorted so I had to use only block: 'end' as my scroll option, I am still looking for alternatives for that.

Of course, there is a need for tracking total amount occurrences and additional logic for index to loop if final occurrence is encountered

1 Like