Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/82.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular2使用javascript突出显示html字符串中的许多单词_Javascript_Html_Css_Angular_Angular2 Template - Fatal编程技术网

Angular2使用javascript突出显示html字符串中的许多单词

Angular2使用javascript突出显示html字符串中的许多单词,javascript,html,css,angular,angular2-template,Javascript,Html,Css,Angular,Angular2 Template,在我的Angular2组件中,我从父组件接收到一个字符串,该字符串包含一些HTML,并被注入到视图中。这部分有效!现在我想突出显示html中的一些第一个单词(注意:这个数字每次都会改变,现在假设是15个) 代码: 1)html字符串(content)包含以下内容: <p>Hello, this is a <span> smaple text</span></p> <p>More things to say here...</p&g

在我的Angular2组件中,我从父组件接收到一个字符串,该字符串包含一些HTML,并被注入到视图中。这部分有效!现在我想突出显示html中的一些第一个单词(注意:这个数字每次都会改变,现在假设是15个)

代码:

1)html字符串(content)包含以下内容:

<p>Hello, this is a <span> smaple text</span></p>
<p>More things to say here...</p>
<p>Perhaps an image as well here, or a link: <a> This is a link here</a></p>
<p>This is very long, did you read this?</p>
toggle() {
    this.content = "<span style=\"background-color: green;\">"+ this.content +"</span>";
  }
您好,这是一个简单的文本

还有很多话要说

也许这里也有一个图片,或者一个链接:这是一个链接

这很长,你读过吗

2)在Angular2中,将该管柱注入组件:

   <div [innerHTML]="content"> </div>

   <button type="submit" (click)="toggle()" >Toggle Highlight</button>

切换高光
3)单击切换btn时:计划在html字符串中计算15个(或指定的)单词,并从开始到单词#15插入一个跨度(绿色背景)

现在,我正在尝试简单地在整个html周围注入一个带有绿色背景颜色的span,如下所示:

<p>Hello, this is a <span> smaple text</span></p>
<p>More things to say here...</p>
<p>Perhaps an image as well here, or a link: <a> This is a link here</a></p>
<p>This is very long, did you read this?</p>
toggle() {
    this.content = "<span style=\"background-color: green;\">"+ this.content +"</span>";
  }
toggle(){
this.content=“”+this.content+”;
}
即使这不起作用,我也尝试了一个类,但它没有被拿起。 在html中插入span还有另一个问题,因为word 15可能位于不同的标记中,这将导致问题


有没有其他方法可以突出显示html字符串中的一些单词的建议?

我认为最好的方法可能是使用指令或管道。基本上是向组件添加指令,检查长度,然后将类添加到元素ref

类似于此:


而不是
span
使用
div
将突出显示的背景色设置为:

toggle() {
  this.content = `<div style="background-color: green;">${this.content}</span>`;
}
toggle(){
this.content=`${this.content}`;
}

您还可以使用反勾号(`)来简化字符串表达式。

正确的方法似乎是而不是使用:

<div [innerHTML]="content"> </div>

AsinnerHTML不支持标记中的任何硬编码样式

相反,在html中使用:

<div #dataContainer></div>

然后在角度TS中:

this.dataContainer.nativeElement.innerHTML =  `<div style="background-color: rgba(0, 210, 0, 0.45);">${this.content}</span>`;
this.dataContainer.nativeElement.innerHTML=`${this.content}`;

你检查我的答案了吗?我喜欢简化字符串表达式的想法,但这仍然不能应用/更新新样式的视图。然而,我现在找到了答案。谢谢