3

I'm trying to insert the YouTube embed API on my angular 2 project, built with angular cli.

I get a "can't find name 'YT'" when I try the approach commented on this question: onYouTubeIframeAPIReady not firing on angular2 web app

My service code looks like this:

loadAPI() {
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

(window as any).onYouTubeIframeAPIReady = function () {
  this.player = new YT.Player('player', {
    events: {
      'onReady': this.onPlayerReady,
      'onStateChange': this.onPlayerStateChange
    }
  });
};

(window as any).onPlayerReady = function (event) {
  event.target.playVideo();
};

(window as any).onPlayerStateChange = function (status) {
  console.log(status.data);
};

I'm not sure where and how should I get the 'YT'structure. I know it comes from the "https://www.youtube.com/iframe_api", but I have no idea of how to get angular to work this out.

  • Based from this [thread](https://github.com/orizens/ng2-youtube-player/issues/4), try to install the latest version. Run `npm i @types/youtube@0.0.28`. Then run `npm install --save`. Also, as stated [here](https://stackoverflow.com/questions/42352944/youtube-d-ts-file-for-the-youtube-iframe-api-to-use-in-angular-2-needed), the YT namespace is defined by the `@types/youtube` package – abielita Aug 22 '17 at 15:47
  • Still no changes after installing @types/youtube. I've tried to add it to tsconfig.json, but had no success. The funny thing is, my text editor knows what 'YT' is, but the compiler doesn't. – Arthur MuffinMad Caputo Aug 22 '17 at 19:22
  • @ArthurMuffinMadCaputo did you fix this? I have the same that my editor sees it but the compiler --prod build doesn't - even if I add `YT: any` – Simon_Weaver Jun 02 '18 at 19:12

1 Answers1

-1

Adding this to my imports for the file referencing YT seems to work.

import 'youtube';

Can someone please explain why! I realize this is similar to import * from 'moment'; but I never really understood that either.

Simon_Weaver
  • 140,023
  • 84
  • 646
  • 689