TJ. TJ. - 4 months ago 1203
Javascript Question

How to set iframe src in Angular 2 without causing `unsafe value` exception?

I am new to Angular 2 without AngularJS experience and working on a tutorial involving the setting of an iframe src attribute:

<iframe width="100%" height="300" src="{{video.url}}"></iframe>

This throws an exception:

Error: unsafe value used in a resource URL context
at DomSanitizationServiceImpl.sanitize...

I have already tried using bindings with
with no success. I am probably missing something and I have had a hard time finding a solution to this.



For RC.6 version use DomSanitizer


And a good option is using pure pipe for that:

@Pipe({ name: 'safe' })
export class SafePipe implements PipeTransform {
  constructor(private sanitizer: DomSanitizer) {}
  transform(url) {
    return this.sanitizer.bypassSecurityTrustResourceUrl(url);


If you use embed tag this might interested for you:

Old version

You can leverage DomSanitizationService like this:

export class YourComponent {
  url: SafeResourceUrl;
  constructor(sanitizer: DomSanitizationService) {
    this.url = sanitizer.bypassSecurityTrustResourceUrl('your url');

And then bind to url in your template:

<iframe width="100%" height="300" [src]="url"></iframe>

Don't forget to add the following imports:

import { SafeResourceUrl, DomSanitizationService } from '@angular/platform-browser';

Plunker sample