Currently, I am in the process of integrating the YouTube IFrame API into my application to deliver course videos to enrolled users. The setup allows me to provide my Angular application with a YouTube embed code, and the IFrame API successfully loads the video upon the initial loading of the course page (as discussed in another post on StackOverflow). However, an issue arises when I navigate using router.navigate to another component and return to the course component - the video and IFrame fail to load.
My assumption is that the document object is created when the page first loads, granting access to the onYouTubeIframeAPIReady method. Once I switch routes, it seems like the previous document object is no longer available.
video.component.ts:
ngAfterViewInit() {
const doc = (<any>window).document;
let playerApiScript = doc.createElement('script');
playerApiScript.type = 'text/javascript';
playerApiScript.src = 'https://www.youtube.com/iframe_api';
doc.body.appendChild(playerApiScript);
}
ngOnInit() {
(<any>window).onYouTubeIframeAPIReady = () => {
console.log('Ready');
this.player = new (<any>window).YT.Player('player', {
height: '100%',
width: '100%',
videoId: 'Bey4XXJAqS8',
playerVars: {'autoplay': 0, 'rel': 0, 'controls': 2},
events: {
'onReady': () => {
},
'onStateChange': () => {
}
}
});
};
}
video.component.html
<div class="embed-responsive embed-responsive-16by9">
<div id="player" class="embed-responsive-item"></div>
</div>
I aim for the video to either re-render or maintain its rendering even if the user navigates to a different component. Please feel free to ask for more information if necessary!