Angular 6 iframe binding

后端 未结 1 1376
再見小時候
再見小時候 2020-12-06 08:36

There is a variable that stores iframe code. I want to bind this in a div, but nothing work.

html:

相关标签:
1条回答
  • 2020-12-06 08:46

    You probably might get a warning saying that it's unsafe HTML. That's why Angular is not rendering it inside the div.

    You'll have to DomSanitize it:

    <div class="top-image" [innerHTML]="yt | safe: 'html'"></div>
    

    Here's the pipe courtesy Swarna Kishore.

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

    Here's a Sample StackBlitz.

    0 讨论(0)
提交回复
热议问题