Use YouTube iframe API with Angular2 and Typescript

MachuPichu picture MachuPichu · Apr 7, 2016 · Viewed 10.7k times · Source

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

Answer

LeOn - Han Li picture LeOn - Han Li · Sep 28, 2017

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...