Angular 2, DomSanitizer, bypassSecurityTrustHtml, SVG

后端 未结 3 525
情深已故
情深已故 2020-11-27 19:01

I\'ve been using DomSanitizer with an SVG in an html string.

Previous to the current version of Angular, this worked just fine:

this.domSanitizer.bypas

相关标签:
3条回答
  • 2020-11-27 19:28

    Use DomSanitizer.bypassSecurityTrustHtml:

    constructor(private sanitizer: DomSanitizer) {
    }
    
    let html = this.sanitizer.bypassSecurityTrustHtml("<svg> blah </svg>");
    

    More information: https://angular.io/docs/ts/latest/guide/security.html#bypass-security-apis

    0 讨论(0)
  • 2020-11-27 19:39

    This can also be done via object bracket notation:

    let safeHtml = this.domSanitizer.bypassSecurityTrustHtml(content);
    console.log(safeHtml["changingThisBreaksApplicationSecurity");
    

    Had to do this because safeHtml.changingThisBreaksApplicationSecurity didn't work for me.

    0 讨论(0)
  • 2020-11-27 19:45

    DEMO : https://plnkr.co/edit/Qke2jktna55h40ubUl8o?p=preview

    import { DomSanitizer } from '@angular/platform-browser'
    
    @Pipe({ name: 'safeHtml'})
    export class SafeHtmlPipe implements PipeTransform  {
      constructor(private sanitized: DomSanitizer) {}
      transform(value) {
        console.log(this.sanitized.bypassSecurityTrustHtml(value))
        return this.sanitized.bypassSecurityTrustHtml(value);
      }
    }
    
    @Component({
      selector: 'my-app',
      template: `
        <div [innerHtml]="html | safeHtml">
        </div>
      `,
    })
    export class App {
      name:string;
      html: safeHtml;
      constructor() {
        this.name = 'Angular2'
        this.html = "<svg> blah </svg>";
      }
    }
    
    0 讨论(0)
提交回复
热议问题