【问题标题】:Angular2 highlight a number of words in html string with javascriptAngular2用javascript突出显示html字符串中的一些单词
【发布时间】:2018-12-12 05:25:32
【问题描述】:

在我的 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>

2) 在 Angular2 中,这个字符串被注入到组件中:

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

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

3) 当点击toggle btn时:计划在html字符串中计算15个(或指定的)单词,并从开始到单词#15注入一个span(绿色背景) ..

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

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

即使这不起作用,我也尝试过上课,但没有被拿起。 在这个 html 中插入跨度还有另一个问题,因为单词 15 可能在不同的标签中,这会导致问题。

是否有其他方法可以突出显示 html 字符串中的多个单词?

【问题讨论】:

  • 你检查我的答案了吗?

标签: javascript html css angular angular2-template


【解决方案1】:

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

类似的东西:

Angular 2/4 : How to check length of input's value using directive?

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

    • 我喜欢简化字符串表达式的想法,但这仍然不能应用/更新新样式的视图。然而,我现在找到了答案。谢谢
    【解决方案3】:

    似乎正确的做法是使用:

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

    因为 innerHTML 不支持标签中的任何硬编码样式。

    在 html 中使用:

    <div #dataContainer></div>
    

    然后在 Angular TS 中:

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

    【讨论】:

      猜你喜欢
      • 2012-09-09
      • 2020-10-16
      • 2011-11-18
      • 1970-01-01
      • 2017-08-29
      • 2014-12-21
      • 1970-01-01
      • 2018-07-31
      • 2020-10-18
      相关资源
      最近更新 更多