Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use YouTube iframe API with Angular2 and Typescript

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

like image 442
MachuPichu Avatar asked Apr 07 '16 05:04

MachuPichu


2 Answers

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...
like image 77
LeOn - Han Li Avatar answered Sep 20 '22 08:09

LeOn - Han Li


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#

like image 41
basarat Avatar answered Sep 20 '22 08:09

basarat