通过 Angular 中的插值将 css 应用于打字稿变量的某些部分

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

假设我在 app.component.ts 中有一个名为 data 的变量,它的类型是 :string.

app.component.html 中,我使用 {{data}}.

等字符串插值向 UI 显示 data 的值

现在我的问题是在 UI 中显示值时,我需要将一些 css 应用于 [=] 中的某些特定字母14=]变量。

例如:

app.component.ts

data : string = "stack overflow"

app.component.html

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

如何使用css高亮溢出字的背景颜色?。而且听说可以用Pipes来修改值。但是这里我需要申请css

还有一个约束条件,最初该值将显示给浏览器;要突出显示的词将来自 input 框。

一种解决方案是使用管道将给定单词提取到单独的 <span> 元素中:

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

然后在组件中有可能以这种方式使用管道<div [innerHTML]="data | letterByLetter"></div>。请注意,我使用了 innerHtml,但您可以改用 DomSanitizer - 这应该更好)

之后您可以决定 span 元素的外观。您可以直接设置 class 或样式。

祝你好运!

您可以使用以下行中的内容:

.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>