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

Issues with Ajax response being added to the table

I am encountering a technical problem with my university project. The task assigned by the professor is as follows: We need to create a static table that lists 3 domain names in order to enhance the performance of the domain availability API. <table&g ...

PHP MySQL - Automatically trigger email notification upon insertion of a new record

Is there a way to trigger an email alert only when a new record is added, not when the user edits input fields in a table? The database I'm working with stores equipment delivery dates. Users schedule deliveries and input the dates into a SQL Server ...

Error: undefined property causing inability to convert to lowercase

I am encountering an error that seems to be stemming from the jQuery framework. When I attempt to load a select list on document ready, I keep getting this error without being able to identify the root cause. Interestingly, it works perfectly fine for the ...

What is the best way to handle promises within the context of updating state in React

Recently, I've been working on a React code snippet focused on creating a text input field. onChangeDestination(url, index) { this.setState(prevState => { const rules = [...prevState.rules]; rules[index] = { ...rules[index], url}; ...

Is it normal for Tailwind animation to loop twice when transitioning between pages in Next.js?

I'm currently utilizing react-hot-toast for displaying alerts and animating them during page transitions. The animation involves a double fade-in effect when transitioning between pages. In my project, I've integrated tailwindcss-animate within ...

Could you explain the distinction between Node.bind() and Template Binding?

Currently, I am exploring the documentation for Google Polymer and have come across two types of data binding - Node.bind() and Template Binding. Can someone please explain the distinction between Node.bind() and Template Binding to me? ...

What is the best way to scroll a specific element within a div container?

I need to enable horizontal scrolling on the user-selected content within a specific div by utilizing its ID. Here is the HTML code snippet: <ion-scroll #scroll scrollX="true" style="height:85px; border-bottom: 2px solid #a01e1e;"> <div class="s ...

Charting data with missing values in Google Charts

I have generated a line chart using php and json to load the data. The issue I am facing is that the chart displays NULL values as 0, which does not look good. My assumption is that I may be formatting the json incorrectly, and what I really need is {"v" ...

Sending a div class as a parameter to a JavaScript function

Wondering if it's possible to pass a div's class into a JavaScript function. I'm using SquareSpace so adding an id to the div is not an option, but it works fine with divs that have ids. JQuery is already loaded. This is my current train of ...

Issue with ADFS 2016 oAuth: Users not being redirected to login page post logout

Having an issue with ADFS 2016 and my Angular application using ng2-adal js for authentication and authorization. After users logout, they are not redirected back to the login page. Debug traces in Event Viewer show the following error: Error: OAuthSignou ...

Notification of Exceeding File Size Limit

Seeking assistance with implementing a 'filesize' error message into a script used for uploading BLOB files to a mySQL server. if (!mysql_connect($db_host, $db_user, $db_pwd)) die("Can't connect to database"); if (!mysql_select_db($dat ...

Optimal technique for adding elements to the DOM using ngFor

My application features a websocket connected to an ngFor loop that populates data from approximately 100 records. Each entry in the list has a button with a click event attached, triggering the creation of a loading spinner via a 'div' element w ...

Observable subscription results in a return of undefined

My observable is being filled with data from the backend using a service. The backend is providing the correct data, but I am having trouble building a pie chart with the values from the observable. The relevant part of the code is as follows: this.dataSe ...

Getting the value from the object that holds the Provider/Consumer using React's Context API

Below is a demonstration using the Context API object with a library called 'react-singleton-context'. Check it out here. In my Menu.js file, I have the code snippet console.log(useSharedDataContext()). This displays an object containing Consume ...

Steps for redirecting from a URL containing location.hash to a different page

Recently, I decided to move a section of one of my webpages from dummy.com/get-started/#setup to its own page at dummy.com/setup. After making this change, I went ahead and deleted the old /get-started page on my website. Many people have bookmarks saved ...

Is it feasible to generate a fixed lighting effect overlay with HTML and CSS?

Is it possible to incorporate a static lighting effect overlay using HTML/CSS? My project consists of an HTML5/JS app with a top navigation bar and a series of cards that are transitioned through using swipe gestures. These cards are displayed in gray ove ...

"Angular 4 is requesting a required get parameter that is currently missing

After running my code, I encountered the following console log error: "'Missing required 'page' parameter". I attempted to set this as a parameter in my get request, and it seemed successful because I was able to view the params as an array ...

What is the best way to insert a variable URL in JavaScript code?

When working with PHP, I often create a declaration similar to the following (taken from an example on Stack Overflow): <script type="text/javascript"> var templateurl = "<?php bloginfo('template_url') ?>"; </script> Subse ...

Guide on Minimizing ES6 with Gulp

I am new to creating a gulpfile.js manually for my project based on Backbone and Marionette. My initial gulp file had the following structure: var gulp = require('gulp'); var $ = require('gulp-load-plugins')(); var browserify = require ...

The error message "unsupported_grant_type" was encountered while using the Django OAuth2 server

Having trouble getting django to accept my POST request for an access token. Despite having the correct parameters and authorization code, I keep receiving an error after sending the follow-up POST request. According to what I've read, the content-ty ...