Reputation: 152
So I need to track time-watched etc of a youtube embed in our app, I figured best way was to use the YouTube iframe API and listen for events, but using (onReady) in the template, then assigning it to a method in controller - the obvious way doesn't seem to work:
The docs show this method(https://developers.google.com/youtube/iframe_api_reference), but it's including script tags in the template, I need an angular way of doing it without putting much ts in your html, and breaking the overall consistency of the project, plus the docs don't show how to do it in Angular2,
Upvotes: 0
Views: 709
Reputation: 152
Since then I found a way by taking a reference from a stackoverflow answer
In your tempelate:
<div #ytPlayer id="ytPlayer"></div>
In ts ngAfterViewinit:
ngAfterViewInit() {
const doc = (<any>window).document;
const playerApiScript = doc.createElement('script');
playerApiScript.type = 'text/javascript';
playerApiScript.src = 'https://www.youtube.com/iframe_api';
doc.body.appendChild(playerApiScript);
}
And then listen for the event iFrame fires on window when it's completed loading api:
(<any>window).onYouTubeIframeAPIReady = () => {
this.player = new (<any>window).YT.Player('ytPlayer', {
height: '500px',
width: '100%',
videoId: 'hHMyZR87VvQ',
playerVars: { 'autoplay': 0, 'rel': 0, 'controls': 2 },
events: {
'onReady': (event) => {
console.log('Player is ready');
},
'onStateChange': (event) => {
}
}
});
};
Then you can call methods like getCurrentTime() on player or whichever variable you assign it to.
Edit: It still uses the document and window object instead of the angular element ref though, I will update this answer once I find a way to do it using window/document.
Upvotes: 1