Reputation: 61
I'm developing a SPA using angular. When the history back button is pressed, the browser changes only the Youtube iframe and not the entire page, I need to press 2 times the back button to go in the full previous page (at the first time the URL is not updated). This happens only when following 2 links with the same route involving the YT iframe element. I need to keep history navigation, so I can't only delete history elements
Component
export class PlayerComponent implements OnInit {
videoName: string;
videoUrl: any;
constructor(
private sanitizer: DomSanitizer,
private route: ActivatedRoute
) {}
ngOnInit() {
this.route.params.subscribe( params => {
this.videoUrl = this.sanitizer.bypassSecurityTrustResourceUrl('https://www.youtube.com/embed/' + params.videoId);
});
}
}
HTML
<div class="embed-responsive embed-responsive-16by9">
<iframe class="embed-responsive-item border border-primary" *ngIf="videoUrl"
[src] = "videoUrl"
allowfullscreen>
</iframe>
</div>
Upvotes: 4
Views: 3993
Reputation: 1
another way is to add key for tracking so that angular will mount and unmount internally:
@for (url of [item.url]; track url) {
<iframe width="100%" height="100%" [src]="url"></iframe>
}
Upvotes: 0
Reputation: 58
I know this question has already been answered, but I solved it using as below:
<div class="advertising" [innerHTML]="htmlValue() | safeHtml">
</div>
htmlValue() {
return `
<iframe src=" + this.iframeUrl() + " frameborder='0' scrolling='no' allow='autoplay'>
</iframe>
`;
}
The pipe safeHtml just return:
constructor(private sanitizer: DomSanitizer) {
}
transform(value) {
return this.sanitizer.bypassSecurityTrustHtml(value);
}
Upvotes: 0
Reputation: 317
You don't need to set "src" in the subscribe, you need to replace url:
.ts
import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
ngOnInit() {
this.route.params.subscribe( params => {
this.iframe.nativeElement.contentWindow.location.replace('https://www.youtube.com/embed/' + params.videoId);
});
}
@ViewChild("iframe") iframe: ElementRef;
.html
<iframe #iframe class="embed-responsive-item border border-primary" *ngIf="videoUrl"
src="about:blank"
allowfullscreen>
</iframe>
Upvotes: 6
Reputation: 15353
One solution is to replace the current URL, this way the iframe is no affected by the browser's back button.
HTML template:
<iframe #iframe></iframe>
TypeScript:
@ViewChild("iframe") iframe: ElementRef;
setUrl(url: string){
this.iframe.nativeElement.contentWindow.location.replace(myUrl);
}
Upvotes: 1