URL sanitization is causing refresh of the embedded YouTube video

Figured it out.

For anyone interested. The problem was the use of this function in my html

   [src]="getTrustedYouTubeUrl(item)"

The reload side effect was gone once I changed the code to calculate the safe url when the data is loaded in my service and changed the iframe binding to this

    <iframe [src]="item.video.safeUrl" scrolling="no" frameborder="0" allowfullscreen></iframe>    

Note thatr I am now binding to a property.


You can keep your original solution and just use changeDetection: ChangeDetectionStrategy.OnPush

<div *ngIf="isVideo(item)">
   <iframe [src]="getTrustedYouTubeUrl(item)" scrolling="no" frameborder="0" allowfullscreen></iframe>          
</div>

I would try to use it with pure pipe

Angular executes a pure pipe only when it detects a pure change to the input value. A pure change is either a change to a primitive input value (String, Number, Boolean, Symbol) or a changed object reference (Date, Array, Function, Object).

Pipe might look like (RC.6 - DomSanitizer becomes instead of DomSanitizationService):

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

And use it as the following:

<iframe [src]="url | safe" frameborder="0" allowfullscreen></iframe> 

Plunker Example (try to push button)


Combined the previous answers to get it working this way:

component.ts (only the relevant parts)

import { DomSanitizer } from '@angular/platform-browser';

constructor( 
  private sanitizer: DomSanitizer   
) {
  this.sanitizer = sanitizer;
}

ngOnInit() {
 this.getTrustedUrl('http://someUrl');
}

getTrustedUrl(url:any){ 
 this.safeUrl = this.sanitizer.bypassSecurityTrustResourceUrl(url);
}

template.html

<iframe      
  [src]='this.safeUrl'>
</iframe>