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

Viewed 937

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.

2 Answers

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>

One solution is use pipe to extract given word into separate <span> elements:

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

Then in component there is possibility to use the pipe in this way <div [innerHTML]="data | letterByLetter"></div>. Notice i've used innerHtml but you can use DomSanitizer instead - which should be better)

After that you are able to decide how the span element should looks. You can set either the class or style directly.

Good luck!

Related