Emphasize a word in a Typescript text by wrapping it in an HTML tag

I've been experimenting with using HTML tags within TypeScript to highlight specific words in a sentence before displaying the sentence in HTML. Despite searching on StackOverflow for various solutions, I haven't been able to find one that works.

Here is an example of the code:

example.sentences = this.sentences.filter((sentence: { Sentence: string | string[]; }) => sentence.Sentence.includes(word))
        .map((sentence: { Sentence: any; }) => sentence.Sentence.replace(new RegExp(word, 'gi'), match => {
          return `<mark class="marking">${match}</mark>`;
        }));

Then I display these sentences in HTML:

<mark *ngFor="let sentence of example.sentences">
      {{ sentence }}
</mark>

The output looks like this:

Alice is in <mark class="marking">wonderland</mark> 

Although it appears as text within the sentence, it's not rendering as HTML.

Is there a way to define this in TypeScript or in HTML in order to change the color of a word within a sentence?

Answer №1

In your example.sentences, you're already outputting HTML so there's no need for additional HTML tags. Here is an alternative approach:

example.sentences = this.sentences.filter((sentence: { Sentence: string | string[]; }) => sentence.Sentence.includes(word))
        .map((sentence: { Sentence: any; }) => sentence.Sentence.replace(new RegExp(word, 'gi'), match => {
          return match;
        }));
<mark *ngFor="let sentence of example.sentences" [innerHTML]="sentence"></mark>

Answer №2

Employ the innerHTML method to identify HTML tags within a string. Here is an example:

<div [innerHTML]="sentence"> </div>

Answer №3

It is recommended to

utilize the constructor method with a private sanitizer parameter: 
// javascript: URLs are risky if manipulated by attackers.
// Angular automatically sanitizes them during data binding, but you have the option
// of explicitly informing Angular to trust this particular value:
this.dangerousHtml = `<mark class="marking">${match}</mark>`;
this.trustedHtml = sanitizer.bypassSecurityTrustHtml(this.dangerousHtml);

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

Storing JWT securely in cookie or local storage for a Node.js/Angular 2 web application

I've been researching how to save jwt tokens in either local storage or cookies but I'm having trouble finding clear instructions online. Can someone provide guidance on how to instruct the server to recognize a user for future sessions? //a ...

What is the reason that specifying the type of function parameters does not result in conversion being

Seeking clarity here. I have a TypeScript function (using version 1.7) that is linked to the change event of a select dropdown in HTML: toggleWorker(stsID: number): void { // get status object by selected status ID let cStatus: Status = this.s ...

Property 'text' is not found on type '{} | Response' in Angular/Node

After making changes to my angular project's package.json by downgrading from version 4.2.4 to 4.1.3 and then upgrading back to 4.2.4, I encountered an error while building the project: $ ng build Your global Angular CLI version (1.5.0) is greater ...

Invoke cloud functions independently of waiting for a response

Attempting a clever workaround with cloud functions, but struggling to pinpoint the problem. Currently utilizing now.sh for hosting serverless functions and aiming to invoke one function from another. Let's assume there are two functions defined, fet ...

Reactive property in the Vue composition API

Within a Vue 3 project that utilizes TypeScript, there are two properties named locale and content: <script setup lang="ts"> import { computed, ref } from 'vue' import { useI18n } from "vue-i18n" import { Landing, Local ...

Maintain the URL state while logging in using angular-oauth2-oidc

In our Angular application, we utilize angular-oauth2-oidc for authentication management with the Code Flow and PKCE. To enable automatic login for users upon app visit, we initialize our app as follows: this.oauthService.configure(authModuleObject); this. ...

Retrieve the user information from Auth0 within the NestJS application

I am currently working on implementing Auth0 authorization in NestJS, but I am unsure of how to retrieve the user's data within the callback URL handler. In a normal express function, this issue could be resolved using the following code. The passpor ...

How do you define prop types when passing them in Nextjs?

Welcome to my page import { InferGetServerSidePropsType, GetServerSideProps } from 'next' import ProductList from '../../component/product/ProductList' export interface Item { title: string price: number } const products ...

What causes the object type to shift away from 'subscribe'?

Currently, I am facing an issue with retrieving a Coupon object from the server using a REST API in combination with Angular. The problem arises when I attempt to access the 'subscribe' method - within the 'subscribe', the object is of ...

When trying to style a Material UI component in Mui v5, no matches for overloads were found

In my attempt to enhance the style of a Material UI Component (TextField) shown in the image, I encountered an error that seems to persist no matter what troubleshooting steps I take. Interestingly enough, I never faced such issues when working with styled ...

How to display a modal within a router-link in Vue 3?

Below are buttons with router-links. However, I only want the calculator button to open a modal. When I execute the code provided, all buttons trigger the modal instead of just the calculator button. Output: https://i.sstatic.net/layQ1.png Router-link C ...

Encountering deployment problems with React and TypeScript involving router on Github Pages

After successfully running locally, I encountered a 404 error when deploying the website using "npm run deploy." My application is built with React and TypeScript, utilizing react-router-dom BrowserRouter for navigation between pages. I've spent 7 h ...

The Server Components render encountered a glitch

Screenshot of the errorI am encountering a strange error only in the production environment. The lack of additional information leads me to believe it may be due to security measures put in place for production. Unfortunately, I have been unable to repli ...

Tips for effectively integrating an admin panel into an Angular project

After building a website with Angular 6, I now need to develop an admin panel to make the site dynamic. What would be the best approach for this task - creating a separate Angular app for the admin panel or incorporating it within the existing website ap ...

Error retrieving the latest token in Angular before the component has fully loaded

I am seeking relevant advice to address my specific need: In my Angular application, I have implemented a jwt-based authentication system. After obtaining a new token and refresh token, I have set up a setTimeout function to ensure the token is refreshed ...

Stop displaying errors with Angular 6 HttpInterceptor

I am looking to implement an HTTPInterceptor to manage all Errors. Below is the code snippet I have written: return next.handle(req) .pipe( catchError((response: any) => { if (response instanceof HttpErrorResponse) { if (response.st ...

NodeJS and TypeScript are throwing an error with code TS2339, stating that the property 'timeOrigin' is not found on the type 'Performance'

I am currently working on a NodeJS/TypeScript application that utilizes Selenium WebDriver. Here is an excerpt from the code: import { WebDriver } from "selenium-webdriver"; export class MyClass { public async getTimeOrigin(driver: WebDriver ...

Troubleshooting the lack of success in enhancing global scope within Typescript

Currently, I am working on a microservices application where I have two very similar services that use practically the same packages. To perform some testing, I decided to add a function to the global scope and modified it slightly to prevent any TypeScrip ...

Distinguishing variations within subcategories that stem from a common origin

In my code example, I have two interfaces that both extend a common base interface. The "String" function takes an argument of type "StringAsset". My expectation was that if I were to call the "String" function and pass it a value of "NumberAsset", TypeScr ...

Issue with Stenciljs custom event not triggering using @Listen decorator

I've been trying to grasp the workings of the custom event emitter. While my mouse events seem to be functioning properly, I'm encountering issues with the custom events. Despite emitting correctly, it appears that the listener is not capturing t ...