How do I construct a YT.Player object and access its properties getCurrentTime()
within an Angular2 Component using Typescript?
I have tried installing several YouTube wrappers via npm, (eg: youtube-player), and added Type definitions for YouTube, with a reference in app.ts:
/// <reference path="../../typings/main/ambient/youtube/index.d.ts" />
but I still get an error when importing, eg: import YouTubePlayer from 'youtube-player';
returns Cannot find module 'youtube-player'.
I've forked the Angular2 preboot/Webpack starter, my source repo is here
You should not need any wrapper, including it yourself is not that much.
1.) include the youtube iFrame API via script tag.
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);
}
2.) register your callback inside onYouTubeIframeAPIReady() function which the Youtube API
will call when the page has finished downloading the JavaScript for the player API.
ngOnInit() {
(<any>window).onYouTubeIframeAPIReady = () => {
this.player = new (<any>window).YT.Player('ytplayer', {
height: '100%',
width: '100%',
videoId: 'YourVideoId',
playerVars: {'autoplay': 1, 'rel': 0, 'controls': 2},
events: {
'onReady': () => {
},
'onStateChange': () => {
}
}
});
};
}
You can also set autoplay
to 0
so it does not play on load.
Now we have the this.player
on the component level, and you can do other manipulations like:
this.player.pauseVideo();
, this.player.loadVideoById('someOtherVideoId')
etc...import YouTubePlayer from 'youtube-player'; returns Cannot find module 'youtube-player'
The library you are trying to use youtube-player
is not the same as the library whole type definitions you are importing : https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/youtube/youtube.d.ts (which is type type definition for the official youtube library)
You can create a declaration your self quite easily in a vendor.d.ts
:
declare module 'youtube-player' {
var foo:any;
export = foo;
}
And you would in no way be worse off than using pure JavaScript.
This is covered here : https://basarat.gitbooks.io/typescript/content/docs/types/migrating.html#
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With