Search code examples
cssangulartypescriptstring-interpolation

Applying css to some part of typescript variable through interpolation in Angular


Let's say I have a variable named data in app.component.ts which is of type :string.

In app.component.html I am showing the value of data to the UI using string interpolation like {{data}}.

Now my question is while displaying the value in a UI, I need to apply some css to some specific letters present in a data variable.

For example:

app.component.ts

data : string = "stack overflow"

app.component.html

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

How to highlight the background color of the word overflow using css?. And I hear that Pipes can be used to modify the value. But here I am in a need of applying css.

And one more constraint is there, initially the value will be displayed to the browser; the word to be highlighted will be coming from input box.


Solution

  • You could use something among the lines of:

    .ts

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

    .html

      <p [innerHTML]="highlightKeyWord('hello world', 'world')"></p>