Utilizing interpolation in Angular to apply CSS styling to specific sections of a TypeScript variable

Suppose I have a variable called data in the app.component.ts file of type :string.

In the app.component.html file, I am displaying the value of data on the UI using string interpolation like {{data}}.

My question is, how can I apply some css to specific letters within the data variable while displaying it in the UI?

For example:

app.component.ts

data: string = "stack overflow"

app.component.html

<p>{{data}}</p>

How can I highlight the background color of the word 'overflow' using css? I know that Pipes are used to modify values, but in this case, I need to apply css.

Additionally, another requirement is that initially, the value will be displayed on the browser, and the word to be highlighted will come from an input box.

Answer №1

If you're looking to add some visual flair to your text, consider this option:

.ts

  addHighlight(sentence: string, wordToHighlight: string) {
      sentence = sentence.replace(wordToHighlight, 
          `<span style="background-color: #35a5f8;">${wordToHighlight}</span>`);
      return this.sanitizer.bypassSecurityTrustHtml(sentence);
  }

.html

  <p [innerHTML]="addHighlight('hello there', 'there')"></p>

Answer №2

To separate a given word into individual <span> elements, one solution is to use a pipe:

@Pipe({
  name: 'letterByLetter'
})
export class LetterByLetter implements PipeTransform {
  transform(value: string): string {
    return value
      .split('')
      .map((letter) => {
        return `<span>${letter}</span>`;
      });
  }
}

In the component, you can utilize the pipe like this:

<div [innerHTML]="data | letterByLetter"></div>
. You can also choose to use DomSanitizer instead of innerHtml if preferred.

You have the flexibility to define the appearance of the span element by setting classes or styles directly.

Best of luck!

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

Unleashed Breakpoint Mystery in Ionic 5 Angular with VSCode

I recently upgraded my Ionic 5 Angular 12 app from Ionic 4 Angular 8. The application is working well and remains stable, but I have encountered some issues while debugging. Firstly, when I use the launch.json file in Visual Studio Code to run the app, it ...

Printing without sufficient paper will result in an incomplete printout

https://i.stack.imgur.com/jNlRr.jpg I am facing an issue with printing the last column "Potensi". The text in this column is not fully printed. How can I resolve this problem? I am using PHP. Thank you ...

What is the best way to set the keyframes CSS value for an element to 0%?

Would like to create a progress indicator div using CSS animations? Check out the JSBin link provided. The desired behavior is to have the div width increase from 30% to 100% when the user clicks on stage3 after stage1, rather than starting from 0%. Althou ...

Tips for waiting for an observable loop

When using my application, the process involves uploading a series of images in order to retrieve the file IDs from the system. Once these IDs are obtained, the object can then be uploaded. async uploadFiles(token: string):Promise<number[]> { let ...

Tips for hiding the overflow scrollbar on Microsoft Chrome when there is no content to scroll

Looking for a solution to hide scroll bars in Microsoft Chrome, but only when there is no content to scroll? The current div and styles always show the horizontal and vertical scroll bars, even when the height exceeds the content. <div style="backgroun ...

When working with data in Angular, make sure to use any[] instead of any in app.component.html and app.component.ts to avoid causing overload errors

I'm new to working with Angular, specifically using Angular 15. I have a Rest API response that I need to parse and display in the UI using Angular. To achieve this, I employed the use of HttpClient for making GET requests and parsing the responses. ...

Implementing the same concept yet yielding diverse variations?

I'm a bit confused as to why a1 is evaluated as false while a2 is considered to be of type boolean. Can someone explain the reasoning behind this discrepancy? type Includes<T extends readonly any[], U> = U extends T[number] ? true : false; type ...

One approach to enhance a function in Typescript involves encapsulating it within another function, while preserving

What I Desire? I aim to create a function called wrap() that will have the following functionality: const func = (x: string) => 'some string'; interface CustomObject { id: number; title: string; } const wrapped = wrap<CustomObject> ...

Troubleshooting the issue with a styled subcomponent in React using Styled Components

Recently, I've delved into React and have been experimenting with creating a Modal component using styled components. My goal is to achieve a similar effect to Framer Motion's motion.div, but utilizing styled components instead. Currently, I hav ...

Steps to stop mat-spinner upon receiving Job Success/Failure Notification from the backend

I have a task that runs asynchronously and takes a long time to complete. When the task starts, I display a mat-spinner with a timeout set at 60000 milliseconds. However, we now have a notification service that provides updates on the job status. I would l ...

The use of DIV tags allows the element to be displayed in an inline

In my project, I decided to add three div tags. The first two are positioned next to each other with the third div tag placed below them. However, when I tried to insert a slideshow into the first div tag, all of the div tags ended up displaying as "block" ...

Center the panel on the page and decrease its width using Bootstrap

I recently incorporated a Bootstrap panel above a search results table - my first experience working with Panels. This panel contains a form with a select menu, allowing users to filter the list of search results based on their selections. Currently, the ...

The issue with making an HTTP POST request in Angular 2

Service: postJson() { var json = JSON.stringify({ "key": "CT", "values": ["FSP", "HMC", "PHYP","hell"] }); let headers = new Headers({'Content-Type':'application/json'}); //let options = new RequestOptions({ ...

Ensure that the textbox remains valid when the reset button is clicked in Bootstrap

After implementing the code for bootstrap textbox and textarea, I encountered an issue when using the reset button. When entering an invalid shop name followed by a valid address and clicking on the Reset button, it resets the form. However, if I then only ...

Testing the functionality of NgRx effect through unit testing

Looking to unit test a functional effect found in this code snippet export const loadUsers = createEffect( (actions$ = inject(Actions), usersService = inject(UsersService)) => { return actions$.pipe( ofType(userActions.getUser), exhaus ...

The dropdown feature within a bootstrap button group is malfunctioning

As part of the web track in cs50, I am working on creating a webpage. My goal is to include options for navigating to the next or previous pages, as well as a dropdown menu with all the pages in between. However, when using Bootstrap's code, the dropd ...

Incorporate OpenLayers 4 into your Angular 5 application

I'd like to integrate OpenLayers 4 into Angular 5 for a project. My main goal is to implement the QuickStart example provided on the official OpenLayers Site. This is what I have accomplished so far: npm install ol --save to download the OpenLayer ...

Padding problem arises when you wrap an image with an anchor tag

I'm having an issue with a div containing an anchor-wrapped image, as there seems to be extra padding at the bottom of the div. How can I remove this? HTML: <div id="lineup"> <div class="line-up-click"> ...

Bootstrap 5 - Create a full-screen modal perfectly aligned with its parent element

BootStrap 5 Incorporating the following layout: <div class="row flex-nowrap"> <div class="left"> <!-- leftbar --> </div> <div class="main overflow-auto position-relative"> <!-- ...

When is the appropriate time to nest CSS class selectors within other class selector definitions?

REVISED 1 After receiving feedback, I made the following changes: .lower-container { justify-content: center; position: absolute; width: 92vw; // height: 46vh; <--- no set height /* nested classes for adjusting position and height of low ...