【问题标题】:Angular2 site stripping my stylingAngular2 网站剥离了我的样式
【发布时间】:2018-05-05 05:18:44
【问题描述】:

我有一个 Angular 2 网站,我正在尝试将一些具有某种样式的 HTML 注入到页面上,如下所示:

<div [innerHTML]="results.top3.TopThreeComments"></div>

results 是调用我们的 Web API 后返回到页面的数据。 results.top3.TopThreeComments 是一个字符串,如下所示:

<p><span style="text-decoration: underline;">underline</span></p>

显然,样式应该为跨度内的文本加下划线,但由于某种原因,角度站点会剥离样式,以便文本在呈现时不带下划线。

这是为什么?

我在谷歌搜索中发现了一个网站:

Angular2 innerHtml binding remove style attribute

建议使用 DomSanitizer:

import { DomSanitizer } from '@angular/platform-browser'
import {PipeTransform, Pipe} from "@angular/core";

@Pipe({ name: 'safeHtml'})
export class SafeHtmlPipe implements PipeTransform  {
  constructor(private sanitized: DomSanitizer) {}
  transform(value) {
    return this.sanitized.bypassSecurityTrustHtml(value);
  }
}

...然后在页面上:

<div [innerHtml]="html | safeHtml"></div>

所以我将上面的打字稿添加到我的主要组件文件(驱动页面)中,并将 safeHtml 插入到我的 div 的 innerHtml 属性中:

<div [innerHTML]="results.top3.TopThreeComments | safeHtml"></div>

这一切只是在 Chrome 控制台中给了我以下错误:

Uncaught Error: Template parse errors:
The pipe 'safeHtml' could not be found ("op3.TopThreeComments">
                    <strong>Comments</strong><br>
                    <div [ERROR ->][innerHTML]="results.top3.TopThreeComments | safeHtml"></div>
                </div>
"): ng:///ResultsAppModule/ResultsComponent.html@73:25

有谁知道我做错了什么。或者是否有其他(最好更简单)的方法来做到这一点?

【问题讨论】:

    标签: angular typescript styling


    【解决方案1】:

    您是否将 SafeHtmlPipe 放入模块声明中,如 Angular2 innerHtml binding remove style attribute 底部所述?这允许在声明它的模块之外看到 safeHtml 符号。

    【讨论】:

      猜你喜欢
      • 2018-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-30
      • 2011-12-14
      • 2022-01-24
      • 2013-04-04
      相关资源
      最近更新 更多