在将这些句子放入HTML之前,我一直尝试使用Typescript内的HTML标签突出显示句子中的特定单词。我在StackOverflow中寻找了几个选项,但我无法指出解决方案。
代码示例为:
example.sentences = this.sentences.filter((sentence: { Sentence: string | string[]; }) => sentence.Sentence.includes(word))
.map((sentence: { Sentence: any; }) => sentence.Sentence.replace(new RegExp(word, 'gi'), match => {
return `<mark class="marking">${match}</mark>`;
}));
然后我从HTML调用这些句子:
<mark *ngFor="let sentence of example.sentences">
{{ sentence }}
</mark>
结果是:
Alice is in <mark class="marking">wonderland</mark>
它看起来是句子中的文本,但没有呈现为HTML。
如何在Typescript或HTML中定义它以更改句子中单词的颜色?
答案 0 :(得分:1)
您已经在example.sentences
中返回HTML,我认为这不是必需的。像这样尝试:
example.sentences = this.sentences.filter((sentence: { Sentence: string | string[]; }) => sentence.Sentence.includes(word))
.map((sentence: { Sentence: any; }) => sentence.Sentence.replace(new RegExp(word, 'gi'), match => {
return match;
}));
<mark *ngFor="let sentence of example.sentences" [innerHTML]="sentence"></mark>
答案 1 :(得分:1)
使用innerHTML标记字符串中的HTML标签。例如,
<div [innerHTML]="sentence"> </div>
答案 2 :(得分:0)
尝试使用
constructor(private sanitizer: DomSanitizer) {
// javascript: URLs are dangerous if attacker controlled.
// Angular sanitizes them in data binding, but you can
// explicitly tell Angular to trust this value:
this.dangerousHtml = `<mark class="marking">${match}</mark>`;
this.trustedHtml = sanitizer.bypassSecurityTrustHtml(this.dangerousHtml);