我们可以在同一个元素上使用 bypassSecurityTrustStyle 和 bypassSecurityTrustHtml 吗?

时间:2021-06-12 19:37:15

标签: javascript angular typescript angular-material

我正在尝试通过 TS 在我的 HTML 中注入 mat-button。

在 col?.cell(element) 中的 innerHTML 中解析的代码如下:

`<button mat-raised-button color="warn">${Constants.BOOKED}</p>`

我的 HTML 是这样的:

<div [innerHTML]="col?.cell(element)"></div>

我创建了一个如下所示的安全管道:

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(private 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}`);
        }
  }
}

现在,如果我在我的 div 中使用 safeHTML 管道作为安全:'html',如下所示:

 <div [innerHTML]="col?.cell(element) | safe: 'html'"></div>

它安全地传递 HTML,但是,我可以使用相同的管道来信任样式,因为样式没有应用于按钮。

0 个答案:

没有答案