Tips for emphasizing the letters of the alphabet used in search functionality with Angular

Is there a way to highlight specific alphabets in the searched list instead of highlighting the entire word? Currently, when filtering the memberOffice and memberFacilities lists based on the alphabet entered in the search field, the entire text is highlighted. However, I would like only the particular alphabet(s) used for the search to be highlighted in the filtered content. Whether it's one alphabet or more, they should be visibly highlighted. Essentially, I want to pinpoint and emphasize the individual alphabets in the filtered list that match my search query.

If you have any insights or suggestions, please share them. Your help is greatly appreciated.

TS:

searchFacility(search) {
    this.sLetter = search;
    let memberFacilities = true;
    if (search) {
      this.dtFacilities.expandedRows = [];
      setTimeout(() => {
        this.dtFacilities.expandedRows = this.dtFacilities.value;
        this.dtFacilities.value.forEach(m => {
          m.memberFacilities.forEach(f => {
            let mySearch = search.toLowerCase();
            let facilityName = f.facilityName.toLowerCase();
            if (facilityName && facilityName.includes(mySearch)) {
              f.isShowMember = false;
              memberFacilities = false;
            } else {
              f.isShowMember = true;
            }
          })
        })
        if (memberFacilities) {
          this.dtFacilities.expandedRows = [];
        } 
      }, 100);

    }

  }

}

In the HTML section, I've utilized the following code snippet:

[class.searcHighlight]

Currently, this set of codes highlights the entire words. I'm looking to make some adjustments but struggling to figure out how to solve this issue.

HTML code snippet related to fList:

<p-column field="facilityName" header="Medical Office Name" [sortable]="true">
          <ng-template let-col let-fList="rowData" pTemplate="body">
            <span>
              <a (click)="selectedFacility(fList.facilityID)" [innerHtml]="fList.facilityName | getHtml : sLetter">
                <strong>{{fList.facilityName}}</strong>
              </a>
              (
              <span>{{fList.facilityType}}</span>)
            </span>
          </ng-template>
        </p-column>
DEMO:

Check out the demo here.

Answer №1

Consider adding the following code snippet to your existing code:

In app.component.ts:

import { Pipe, PipeTransform } from '@angular/core';
        import { DomSanitizer } from '@angular/platform-browser'


    @Pipe({ name: 'getHtml' })
export class HighlihtText implements PipeTransform {
  constructor(private sanitized: DomSanitizer) { }
  transform(value, searchText) {
    if(searchText=='' || !searchText){
      return value;
    }
    console.log("value="+value)
    var str = value.toLowerCase();
    searchText=searchText.toLowerCase();
    var currHtml = "";
    var ind = -1;
    while (str.indexOf(searchText) >= 0) {
      ind = str.indexOf(searchText);
      createHtml(value.substr(0, ind),value.substr(ind,searchText.length))
      str = str.substr(ind + searchText.length)
      value=value.substr(ind + searchText.length);
    }
    if (str.length > 0) {
      currHtml = currHtml + str;
    }
    function createHtml(nohighlighText,match) {
      console.log(nohighlighText)
      currHtml = currHtml + nohighlighText + "<span class=\"searcHighLight\" >" + match + "</span>"
    }
    return this.sanitized.bypassSecurityTrustHtml(currHtml);
  }

}

In app.component.html, make the highlighted search result changes here:

<a class="userlist" (click)="selectedFacility(memberFacility.facilityID)" [innerHtml]="memberFacility.facilityName | getHtml : sLetter">
                      </a>

In app.module.ts, declare the newly created pipe:

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

 declarations: [ AppComponent, HelloComponent,facilityFilterPipe,HighlihtText ],

To address the ALL search issue with reset, add the following line at the end of the searchFacility(..) method in app.component.ts:

if(search==''){
      this.searchFname="";
    }

Additionally, initialize the variable searchFname as follows:

 searchFname:String;

For highlighting the fList element as well, update the code snippet like so:

<a (click)="selectedFacility(fList.facilityID)">
                <strong  *ngIf="sLetter!=''" [innerHtml]="fList.facilityName | getHtml : sLetter"></strong>
                <strong *ngIf="sLetter==''">{{fList.facilityName}}</strong>
              </a>

Don't forget to initialize sLetter in app.component.ts's ngOnInit() method:

this.sLetter="";

You can find a working example on StackBlitz here: https://stackblitz.com/edit/angular-ku9aaj

If you have any questions or concerns, feel free to reach out!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Enhancing the appearance of unvisited links with background styles

I am endeavoring to incorporate an icon into all unvisited links on a specific Wordpress category page. Below is the CSS code that I am utilizing. It has been placed at the conclusion of my final CSS file. .category-xyzzy .entry-title a:link { background ...

The body parser is causing issues with decoding base64 strings

When my mobile app sends a base64 string to my Express server via a POST request, the image is transmitted to a Google client endpoint. However, an error is returned saying: Provided image is not valid code: 400, 0|index | errors: [ 0|index | { 0 ...

Implementing the SendOwl License API for theme licensing

Currently developing a Shopify theme for sale and exploring licensing options Considering using SendOwl's API for licenses - Shopify themes support html/css/js/liquid, no server-side code, so JavaScript is required. Can the SendOwl API be used to v ...

Having trouble with hover effects not working on links due to the container? Here's a solution for you

I would like to create a layout with 3 columns for menu, story, and description. Each story should have its own unique description. Everything was working fine until I added a div to the middle column. The same issue arose with the right column but I manag ...

Utilizing React Native for seamless deep linking with automatic fallback to a webpage, including the ability to pass

I am currently working on a project that involves a website built with React and a React-native app for camera functionality and data processing. On the website, there is a button that opens the camera in the React-native app through deep-linking. This pa ...

Tips for efficiently handling navigation re-rendering on a Single Page Application using Vue.js

I am currently in the process of developing a Single Page Application using Vue.js. The structure involves having a template in App.vue which includes a navigation bar followed by a router-view component. When a user attempts to log in, a modal window appe ...

The HTML code is displayed on the page as source code and is not run by the browser

Here is the code snippet I am using: $link = "<a class=\"openevent\" href=\"$finalUrl\" target=\"_blank\">Open Event</a>"; foreach ($spans as $span) { if ($span->getAttribute('class') == 'categor ...

Encountering difficulties while attempting to import a module in Next.js

My attempt to import the Zoom Web SDK module into my Next.js project encountered an error due to the undefined window object. Simply trying to import the websdk module resulted in this unexpected issue https://i.stack.imgur.com/NDRoC.png I am using Next ...

After making an Ajax call using AngularJS in a PHP file, I expected to receive only a success or fail message. Instead, I received the entire HTML page code along

After making an Ajax call using AngularJS in a PHP file, I expected to receive only a success/fail message. However, I ended up receiving the full HTML page code along with tags. Here is my AngularJS code: $http.post('ajax_Location.php',{ &apos ...

Background Patterns on Webpages

My website has a lovely gradient background on the html tag in css, while the body tag showcases a seamless pattern repeating on both the x and y axes. Everything was looking great until I checked the website on an iPad/iPhone in portrait mode, where the ...

Issue with Angular modal popup not repositioning upon clicking elsewhere on the page

I have encountered an issue with modal popups on my website. Specifically, I have approximately 100 table elements and when I try to edit the element #100, the modal popup appears at the bottom of the page. However, if I scroll back up and click on eleme ...

Select box failing to display default value

I am dealing with a specific data structure: $scope.personalityFields.traveller_type = [ {"id":1,"value":"Rude", "color":"red"}, {"id":2,"value":"Cordial", "color":"yellow"}, {"id":3,"value":"Very Friendly", "color":"green"}, ]; Also, there is a se ...

Is Fetch executed before or after setState is executed?

I've encountered an issue while trying to send data from the frontend (using React) to the backend (Express) via an HTML form, and subsequently clearing the fields after submission. The code snippet below illustrates what I'm facing. In this scen ...

Encountering Angular error when trying to assign an undefined array to another array while using mock data

Attempting to conduct unit testing on a component involving the retrieval of 'Groups' data through a data resolver class. Below is the corresponding code: export class GroupsComponent implements OnInit, OnDestroy { group: IGroup; groups: IGro ...

Dealing with numerous errors from various asynchronous pipes in angular - a comprehensive guide

I am facing an issue with 2 mat-select elements in my component, both of which utilize the async pipe: <div class="flex-col"> <mat-label>Issue Desc </mat-label> <mat-form-field> < ...

Universal Module Identifier

I'm trying to figure out how to add a namespace declaration to my JavaScript bundle. My typescript class is located in myclass.ts export class MyClass{ ... } I am using this class in other files as well export {MyClass} from "myclass" ... let a: M ...

When working with Laravel and submitting a form using the `multipart/form-data` encoding type, you may encounter the

When sending a request that includes form data object with some data from angular 4 to laravel api, sometimes the request data is received correctly and other times it is null, referred to as 'empty request.' Below are the details of my request: ...

Steps for Disabling Autocomplete in a JSP Page

How can I prevent the browser from remembering the username and password on my JSP page after submitting the form? I've already tried using autocomplete=off in the JSP code. <form name="indexFrm" id="indexFrm" autocomplete="off" method="post"> ...

Can a personalized user permission prompt be designed for HTML5 APIs?

Can a consistent custom user permission request dialog be designed for HTML5 APIs, such as geolocation or getUserMedia, to ensure uniform appearance on all browsers? ...

"Choosing multiple options in Select2 causes it to constrict within a Bootstrap 4 inline

I am facing an issue where the field shrinks drastically when I type in it. Here's a code snippet that showcases this problem: $(function() { $("select").select2({ placeholder: "Select a word", width: "100%" }); }); <link rel ...