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

A guide on utilizing Angular service within a component to successfully submit form data to an API

I am currently facing an issue with my Angular 6 form and service setup. I have a service that can successfully handle GET requests to a web API, but I am struggling with making POST requests from my form to the API. The code I currently have is not workin ...

switching the content of an element using Javascript

I'd like to switch between two icons when clicking on .switch and apply the style of .nightTextNight to .nightText, my JavaScript code is working well everywhere except here. Is there a simpler way to achieve this? I currently have to create two clas ...

Leverage the power of TypeScript custom transformer and project reference for enhanced

I am currently working on a project that involves using both project references and custom transformers. The issue I am facing is that project references require the use of TSC for incremental compilation, but when TSC is used, the transformers are not app ...

Adding a <span> element within an <h1> tag in WordPress

I am attempting to create this layout in Wordpress using the code <h1>This is my <span>title</span></h1>, but I am unsure how to incorporate a <span> tag within the <?php the_title(); ?> function. After consulting the c ...

Utilizing Host Styles in Angular2 Components

In the midst of developing a custom form component for my Angular project, I am facing challenges with styling. I wish to allow variable widths for the input element and have them controlled by the host component. For instance: <my-input class="input" ...

The variable 'key' is declared in the Google Chrome extension V3 local storage, but it appears that its assigned value is never actually accessed

In my TypeScript code, I have defined a function like so: setLocalStorage: async (key: string, value: string): Promise<string> => { return new Promise((resolve, reject) => { chrome.storage.local.set({ key: value }, funct ...

What is the best way to accomplish this using typescript/adonis?

While exploring some code examples on Bitbucket, I came across a sample that demonstrated how to paginate query results using JavaScript. However, as I attempted to apply it in my project, I encountered difficulties in declaring the types required for the ...

"Define a TypeScript function type that can return either an object or a string depending on whether it succeeds or fails

I encountered an issue with a function that either returns a Promise on success or a string on error. async create(createDebtorDto: CreateDebtorDto): Promise<Debtor> { console.log("createDebtorDto", createDebtorDto) try{ const createdD ...

Unable to connect to web3 object using typescript and ethereum

Embarking on a fresh project with Angular 2 and TypeScript, I kicked things off by using the command: ng new myProject Next, I integrated web3 (for Ethereum) into the project through: npm install web3 To ensure proper integration, I included the follow ...

Is it necessary to use an EventEmitter explicitly when performing two-way binding in Angular 2?

If I have a Kitchen class structured like this: @Component({ template: ` <kitchen [(kitchenLunch)]=lunch></kitchen> ` }) export class House { private lunch: Lunch; } The House component: Includes a sub-component Ki ...

Enable a single column to scroll until the content is fully displayed, and then stay in a fixed position

My HTML content consists of two columns, with the first column being a sidebar that should have limited content. The second column holds the main content and can span several pages. The desired functionality is for the first column to scroll until the end ...

What is the best way to retrieve information utilizing Http.get within my project?

I have a TypeScript file containing user data: File path: quickstart-muster/app/mock/user.mock.ts import {User} from "../user"; export const USERS:User[]=[ new User(....); ]; I have a service set up at: quickstart-muster/app/services/user.service.ts ...

Issue encountered with redux-toolkit's createAsyncThunk functionality

Here is how I implemented the deleteDirectories method in redux: export const deleteDirectories = createAsyncThunk( "directories/deleteDirectories", async (id, thunkAPI) => { try { const response = await axios.delete(`${url}direc ...

Several dropdown menus within the same container, working independently of each other

I recently encountered an issue with a drop-down navigation bar. When I have multiple drop-downs and click on one, it opens as expected. However, if I then proceed to click on another drop-down while the first one is already open, both of them remain open ...

Encountering an issue while trying to launch an Angular application on localhost. Vendor.js resource failed to load

Whenever I compile the code, it runs successfully. However, when I try to serve the application using 'node --max-old-space-size=8192', even though it compiles without any errors, when I open the app in a browser, it returns an error saying "Cann ...

Guide to linking Angular 2 with a backend server

Running my angular 2 application with Node.js and the backend is hosted on a Wildfly server on separate servers (but same machine). I am looking to make an API call from the frontend to retrieve data. Do you think this setup will work successfully? ...

Looking for assistance with transforming my Angular 2 component into an npm package

After successfully creating a component in Angular 2, my next step is to convert it into an npm library for easy installation. npm install Despite installing Angular CLI and searching online, I have been unable to find clear instructions on how to effe ...

Angular Elements generates compact, single-line HTML output

It's incredibly frustrating how browsers handle inline-block elements, creating invisible margins when placed side by side. You can experience this "bug" firsthand here: http://jsfiddle.net/8o50engu/ Interestingly, if these elements are on the same l ...

Exploring ways to enhance Bootstrap Navigation by adding extra link options. Seeking a resolution using jQuery

Are you looking for a solution to handle site navigation with a larger number of links? When more links are added, they display in multiple lines which might not be the desired layout. You can view an example of this issue in the attached image: See here a ...

Is it possible to utilize the ternary operator to handle classnames when working with CSS modules?

I am experiencing difficulty implementing a styling feature using the ternary operator within an element's className. My goal is to have three buttons that render a specific component when clicked. Additionally, I want to change the background color ...