0

I'm getting couple of posts from REST API and parsing them with:

<div class="row" *ngFor="let Post of Posts">
  Some output
</div>

Some of them are having youtube_url but most of them are not so i am using the following snippet to add youtube iframe for those posts with an youtube_url.

<div class="embed-responsive embed-responsive-16by9" *ngIf="Post.youtube_url" style="margin-bottom: 5px;">
  <iframe class="embed-responsive-item" [src]=Post.youtube_url allowfullscreen></iframe>
</div>

My issue right now is that i am getting the following error:

ERROR Error: unsafe value used in a resource URL context (see http://g.co/ng/security#xss)
at DomSanitizerImpl.sanitize (platform-browser.js:4506)
at setElementProperty (core.js:10753)
at checkAndUpdateElementValue (core.js:10673)
at checkAndUpdateElementInline (core.js:10607)
at checkAndUpdateNodeInline (core.js:13889)
at checkAndUpdateNode (core.js:13836)
at debugCheckAndUpdateNode (core.js:14729)
at debugCheckRenderNodeFn (core.js:14708)
at Object.eval [as updateRenderer] (HomeComponent.html:17)
at Object.debugUpdateRenderer [as updateRenderer] (core.js:14693)

I had found multiple questions about this one, but none of them with my above conditions.

So, how can i do this?

1 Answers1

0

You need to tell your dom that the url is safe. You can do that by implementing this pipe in your app:

import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer } from "@angular/platform-browser";

@Pipe({ name: 'safeUrl' })
export class SafeUrlPipe implements PipeTransform {
    constructor(private sanitizer: DomSanitizer) { }

    transform(url) {
        return this.sanitizer.bypassSecurityTrustResourceUrl(url);
    }
}

... and then use it in your template like this:

<div class="embed-responsive embed-responsive-16by9" *ngIf="Post.youtube_url" style="margin-bottom: 5px;">
      <iframe class="embed-responsive-item" [src]="Post.youtube_url | safeUrl" allowfullscreen></iframe>
</div>
FAISAL
  • 33,618
  • 10
  • 97
  • 105