首页 > 解决方案 > 如何从 Angular 方法返回 HTML 表达式?

问题描述

所以标题可能不是最好的......但我想到了没有更好的东西:

我想在结果列表中突出显示搜索关键字……这就是为什么我在为这个问题苦苦挣扎的原因。CSS:

highlightText{
 font-weight: bold;
}

在打字稿中:

myVariable = "hello world";
keyword=" bonjour";

highlightText(text: string){
   return text.replace(keyword, "<span class='highlightStyle'>"+keyword+"</span>");
}

在 HTML 中:

<div>
    {{highlightText(myVariable)}}
</div>

在屏幕上我看到整个文本..:

<span class='highlightStyle'>bonjour</span> 世界

但是我真的很期待: bonjour world

yuhhuu 就是这样 :D

任何的想法?

谢谢,Csaba

标签: angulartypescript

解决方案


最好使用管道 - 性能更高(函数针对每个更改检测周期运行,而管道仅在其输入参数更改时运行)

看看这个https://stackblitz.com/edit/angular-highlight-pipe


推荐阅读