When using Angular 2, the `onYouTubeIframeAPIReady` function may not be able to locate the `YT` name, even if it is defined on the

As part of my efforts to track when a user pauses a YouTube video (link to the question), I have been utilizing the onYouTubeIframeAPIReady callback method in Angular2.

I am facing similar challenges as discussed here and here.

Following the recommendations, I resorted to using

(window as any).onYouTubeIframeAPIReady = function () {}
.

Within my onYouTubeIframeAPIReady function, the code looks like this:

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

However, I encounter the following error from my TypeScript linter:

Argument of type '{events: {'onReady':(event:any) => void; 'onStateChange': (event:any)=>void;};}' is not assignable to parameter of type 'PlayerOptions'

You can find my minimal example repository here:

git clone https://github.com/Atticus29/dataJitsu.git
cd dataJitsu
git checkout stackoverflow
npm install
ng serve

Answer №1

By utilizing window['YT'] in place of just YT, you can resolve this issue:

ngOnInit() {
  var player;

  window['onYouTubeIframeAPIReady'] = function() {
    player = new window['YT'].Player('video', {
      events: {
        'onReady': onPlayerReady,
        'onStateChange': onPlayerStateChange
      }
    });
  }

  function onPlayerStateChange(event){
    if (event.data == window['YT'].PlayerState.PAUSED) {
      console.log(player.getCurrentTime());
    }
  }

  function onPlayerReady(event) {
    document.getElementById("pause").addEventListener("click", function() {
      player.pauseVideo();
    });
    document.getElementById("play").addEventListener("click", function() {
      player.playVideo();
    });
  }

  if (!window['YT']){
    var tag = document.createElement('script');
    tag.src = "//www.youtube.com/player_api";
    var firstScriptTag = document.getElementsByTagName('script')[0];
    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for implementing a reusable instance of a class in (SSR) React (comparable to a @Bean in Spring)

I am currently developing a new application using Next.js and React (Server Components) in TypeScript. In order to showcase and evaluate the app, I need to support two different data sources that provide identical data through separate APIs. My goal is to ...

Angular HTTP Patch method requires explicitly defined HTTP options as input parameters

I encountered a challenge with using Angular's HTTP patch method and noticed that the overloaded function patch(url, body, options) only accepts hardcoded values for HTTP options. An example of a hardcoded approach that works: patchEntity(id: number) ...

Is it possible to incorporate personalized middleware into the development server of an Angular CLI application?

Is it possible to extend the Angular CLI's proxy to incorporate custom Express middleware for our organization's unique authentication model requirements? Create React App allows this through exposing the Express app instance and allowing app.us ...

Verification based on conditions for Angular reactive forms

I am currently learning Angular and working on creating a reactive form. Within my HTML table, I have generated controls by looping through the data. I am looking to add validation based on the following cases: Upon page load, the Save button should be ...

Retrieve a collection of Firestore documents based on an array of unique identifiers

I have a Firestore collection where one of the values is an array of document IDs. My goal is to retrieve all items in the collection as well as all documents stored within the array of IDs. Here is the structure of my collection: https://i.sstatic.net/rA8 ...

Utilizing template logic that draws from a fusion of two distinct texts

Looking to display two different texts depending on a boolean value. Here is what I attempted: <div name="health-plans" *ngIf="!flagon"> Test<br />data </div> <div name="health-plans&quo ...

Footer missing from Tanstack React table

Library Version: "@tanstack/react-table": "^8.2.6", I have been attempting to include footers in my table without success. Despite setting static footer text with a fixed value, I am unable to render any dynamic values similar to how h ...

Discovering the worth of a variable outside of a subscription or Promise within Ionic 3

Apologies for my English. I am encountering an issue when attempting to view the results of a REST API using both subscribe and Promise methods. Within my provider, I have the following code: Provider: import { HttpClient } from '@angular/common/h ...

Leveraging the Cache-Control header in react-query for optimal data caching

Is it possible for the react-query library to consider the Cache-Control header sent by the server? I am interested in dynamically setting the staleTime based on server instructions regarding cache duration. While reviewing the documentation, I didn&apos ...

Executing the Onclick event within a primeNG menu bar

Need help with triggering the On-click event in PrimeNG? If you're looking to navigate to the UserFormComponent.html page and add a new user when clicking on the 'New' menu bar using PrimeNG, here's how you can achieve it: You can fin ...

How can we use tsyringe (a dependency injection library) to resolve classes with dependencies?

I seem to be struggling with understanding how TSyringe handles classes with dependencies. To illustrate my issue, I have created a simple example. In my index.tsx file, following the documentation, I import reflect-metadata. When injecting a singleton cl ...

Manipulating CSS Class Properties Using JavaScript

In my JavaScript application, there is a functionality that loads a list of items for users to click and view detailed information in a separate div on the page. Users should be able to interact with and make modifications to these individual item overview ...

How come the hook keeps triggering endlessly in a loop when I try to pass the updated props?

I've encountered an issue with a custom hook I created for making HTTP requests. The problem is that the request seems to be firing in an endless loop, and I'm unsure of what's causing this behavior. My intention is for the request to only t ...

Is it possible for a button to be assigned to a variable upon creation, but encounter an error when trying to

const button:Element = document.createElement("button");//This works fine const button:HTMLButtonElement = document.createElement("button");//This works too const button2:Element = document.getElementsByTagName("button");//Why does this give an error? con ...

Building an interactive menu in Angular: A step-by-step guide

I am working with an Interface that looks like this: export interface INavData { name?: string; url?: string | any[]; icon?: string; } To populate this Interface, I use the following data structure: export const navItems: INavData[] = [ { ...

Restricting array elements through union types in TypeScript

Imagine a scenario where we have an event type defined as follows: interface Event { type: 'a' | 'b' | 'c'; value: string; } interface App { elements: Event[]; } Now, consider the following code snippet: const app: App ...

Should every component be imported in app.module.ts?

Let's say I have three components: componentA, componentB, componentC. Is it necessary to import all three components? Why or why not? For example, in the following section of code in app.module.ts: app.module.ts @NgModule({ declarations: [** ...

Exploring the differences in object shapes using TypeScript

I'm currently working on defining an object that has the ability to hold either data or an error. export type ResultContainer = { data: any; } | { error: any; }; function exampleFunction():ResultContainer { return { data: 3 } } ...

Issue with running gulp ser on first attempt in SPFX

Every time I try running gulp serve, I encounter the following issue: Error: Unable to locate module '@rushstack/module-minifier-plugin' Please assist me with this problem. Thank you! ...

Using Angular and Okta together can bring a seamless experience for your users. Learn how to properly use the redirect

I have integrated Okta for user authentication in my Angular 13 application. I followed the guidelines provided by Okta to utilize their SDK, but I am facing issues defining the redirectionUrl with the HashLocationStrategy. Upon logging in, I encounter a ...