1. 使用 html
管道 和bypassSecurityTrustHtml()
来规避 angular
的脚本净化
const html = `<div style="color: #0067ff">Hello World!</div>`
<p [innerHTML]="html | html"></p>
ng g p pipes/html --skip-test
// pipes/html.pipe.ts
import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
@Pipe({
name: 'html'
})
export class HtmlPipe implements PipeTransform {
constructor(private sanitizer: DomSanitizer) {}
transform(style: any) {
// 对传入的 html 绕过安全检查
return this.sanitizer.bypassSecurityTrustHtml(style);
}
}
网友评论