Angular 中默认将所有输入值视为不受信任。当我们通过 property,attribute,样式,类绑定或插值等方式,将一个值从模板中插入到 DOM 中时,Angular 会自帮我们清除和转义不受信任的值。此时,我们 DomSanitizer 对象中,提供的 sanitize() 方法来解决上述问题。
在 Angular 中使用 [innerHTML] 时,如果内容被转义了,可能是由于 Angular 默认的安全策略。Angular 为了防止 XSS(跨站脚本攻击)对插入的 HTML 内容进行了一些转义处理。为了让 Angular 正确地渲染 HTML 内容,你需要使用 Angular 的 DomSanitizer 服务来绕过这些安全措施。
import { Component } from '@angular/core';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
@Component({
selector: 'app-example',
template: `<div [innerHTML]="safeHtml"></div>`,
})
export class ExampleComponent {
safeHtml: SafeHtml;
constructor(private sanitizer: DomSanitizer) {
const htmlContent = '<p>Some <strong>HTML</strong> content</p>';
this.safeHtml = this.sanitizer.bypassSecurityTrustHtml(htmlContent);
}
}
以下是一个完整的示例组件,展示了如何使用 DomSanitizer 来安全地插入 HTML 内容。
import { Component } from '@angular/core';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
@Component({
selector: 'app-example',
template: `
<div [innerHTML]="safeHtml"></div>
`,
})
export class ExampleComponent {
safeHtml: SafeHtml;
constructor(private sanitizer: DomSanitizer) {
const htmlContent = '<p>This is <strong>safe</strong> HTML content</p>';
this.safeHtml = this.sanitizer.bypassSecurityTrustHtml(htmlContent);
}
}
在这个例子中, safeHtml 属性包含了经过 DomSanitizer 处理的 HTML 内容,并被安全地插入到模板中。

