忽略用户注入的HTML,但呈现开发人员的html-Angular

时间:2018-08-10 12:22:10

标签: html angular

我想在Angular中创建一个条款和条件组件,该组件将从数据库中检索。条款和条件将包括html和用户数据(用户的公司)。之所以在T&C中包含html是因为我想保持可变性,将来还会更改文本和布局。

如果我有以下条款和条件:

<p>The company USERCOMPANY will have the responsibility to accept the T&C</p>

*其中USERCOMPANY将由用户的公司代替

Angular和HTML中有什么解决方案,以便它将呈现我的html标签(在这种情况下为p标签),但如果他添加了诸如<strong>My Company</strong>或js脚本之类的内容,则不会呈现用户输入?

1 个答案:

答案 0 :(得分:1)

如果两个都分开存储,则可以使用(快速且肮脏的)在USERCOMPANY中转义该值:

USERCOMPANYstring.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#039;");

使用某种替换将转义的usercompany字符串包含到其他html代码中,然后使用safe管道将其放入html中: <p [innerHTML]="yourVariable | safe: html"></p>

安全管道:

import { Pipe, PipeTransform } from "@angular/core";
import {
  DomSanitizer,
  SafeHtml,
  SafeStyle,
  SafeScript,
  SafeUrl,
  SafeResourceUrl
} from "@angular/platform-browser";

@Pipe({
  name: "safe"
})
export class SafePipe implements PipeTransform {
  constructor(protected sanitizer: DomSanitizer) {}

  public transform(
    value: any,
    type: string
  ): SafeHtml | SafeStyle | SafeScript | SafeUrl | SafeResourceUrl {
    switch (type) {
      case "html":
        return this.sanitizer.bypassSecurityTrustHtml(value);
      case "style":
        return this.sanitizer.bypassSecurityTrustStyle(value);
      case "script":
        return this.sanitizer.bypassSecurityTrustScript(value);
      case "url":
        return this.sanitizer.bypassSecurityTrustUrl(value);
      case "resourceUrl":
        return this.sanitizer.bypassSecurityTrustResourceUrl(value);
      default:
        throw new Error(`Invalid safe type specified: ${type}`);
    }
  }
}

这将清除来自数据库的输入,转义字符(即USERCOMPANY)不应显示为html,但是其余部分将是普通html,并且由于已对其进行了消毒而被Angular信任。