Reputation: 25
I can't get the YouTube Iframe API to load in my Angular App without refreshing the page. Upon page load the iframe loads without any issues, but when navigating to the page via page routing the API won't get called and the iframe does not render. I've seen some solutions online but they don't appear to work.
Any help would be much appreciated.
**HTML**
<div *ngIf="selectedVideo && ytLoading">
<div id="player" style=" height: 500px; width: 100%;">
</div>
Component
ytLoading = false;
player: any;
init() {
this.ytLoading = true;
console.log('loading init',this.ytLoading)
if (this.ytLoading && window['YT'] ) {
this.cueVideoById(this.selectedVideo);
return;
}
var tag = document.createElement('script');
tag.src = 'https://www.youtube.com/iframe_api';
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
window['onYouTubeIframeAPIReady'] = () => this.cueVideoById(this.selectedVideo);
console.log('WINDOW OBJ 2', window['YT'], 'API SCRIPT 2', tag )
}
ngOnInit() {
this.ytLoading = false;
this.init();
}
ngOnDestroy() {
this.ytLoading = false;
window['onYouTubeIframeAPIReady'] = null;
if (this.player) {
this.player.destroy();
}
}
cueVideoById(selectedVideo) {
console.log('hits via init', selectedVideo)
this.player = new window['YT'].Player('player', {
videoId: selectedVideo.id,
playerVars: {
modestbranding: 1,
controls: 1,
disablekb: 1,
rel: 0,
showinfo: 0,
fs: 0,
playsinline: 1
},
events: {
'onStateChange': this.onPlayerStateChange.bind(this),
'onError': this.onPlayerError.bind(this),
'onReady': this.onPlayerReady.bind(this),
}
});
}
Upvotes: 0
Views: 128
Reputation: 25
The issue was resolved by updating the ngOnDestroy method
ngOnDestroy() {
window['YT'] = null;
if (this.player) {
this.player.destroy();
}
}
Upvotes: 1