Use YouTube iframe API with Angular2 and Typescript
Asked Answered
T

4

5

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

Timtima answered 7/4, 2016 at 5:37 Comment(1)
Did you ever find a solution to this?Ertha
D
9

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:

  • pause: this.player.pauseVideo();,
  • load other video this.player.loadVideoById('someOtherVideoId') etc...
Dow answered 28/9, 2017 at 17:14 Comment(0)
S
5

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)

Fix

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.

More

This is covered here : https://basarat.gitbooks.io/typescript/content/docs/types/migrating.html#

Sulfonal answered 7/4, 2016 at 6:26 Comment(1)
Thanks @basarat, I'm new to Typescript, and writing my own typescript definitions for a complex npm module seems quite difficult. Could you please provide a real example? or refer to an existing definition?Timtima
C
4

I also had this problem. Like basarat says, the youtube.d.ts typings definitions are not for the youtube-player package.

I followed basarat's advise and created a vendor.d.ts in my typings folder and added the definition (typings/vendor.d.ts):

declare module 'youtube-player' {
    var YouTubePlayer: any;
    export = YouTubePlayer;
}

The above was not sufficient to get it working though, I needed one further step. I used a different import statement to finally get it to work (MyController.ts):

import * as YouTubePlayer from 'youtube-player';

export class MyController {
    constructor() {
        let player = YouTubePlayer('playerid');
        player.loadVideoById('M7lc1UVf-VE');
        player.playVideo();
    }
} 
Comte answered 16/7, 2016 at 22:45 Comment(1)
I tried this, but got an error similar to 'TS2304 name 'YouTubePlayer' could not be found'. Do you have any ideas why it wouldn't work? I followed the exact same steps.Lancinate
P
1

Give https://github.com/orizens/ng2-youtube-player a try! Its written in ng2/ts and may support your needs.

Padus answered 15/10, 2016 at 15:37 Comment(1)
Important: It's not free for commercial use!Crenation

© 2022 - 2024 — McMap. All rights reserved.