Search code examples
node.jsangulartypescripttwitch

Angular how can I use embed script in Component


I'm trying to set up in Angular a way of only showing Twitch player if the stream is online, so in the Documentation there is this inline HTML:

<script src= "https://player.twitch.tv/js/embed/v1.js"></script>
<div id="<player div ID>"></div>
<script type="text/javascript">
  var options = {
    width: <width>,
    height: <height>,
    channel: "<channel ID>",
    video: "<video ID>",
    collection: "<collection ID>",
  };
  var player = new Twitch.Player("<player div ID>", options);
  player.setVolume(0.5);
</script>

Of course though in Angular Components we can't use < script > tags and I don't think it's currently possible to use require or import to use this in my components TypeScript.

So how would I go about adding this functionality? I understand what to do after I can actually reference that script tag.


Solution

  • You can create a script tag dynamically, but I think it's easier to just download the script and put it in assets folder and then add the script to script list in angular.json

    or you can add the script to index.html head section

    index.html

    <head>
        <script src= "https://player.twitch.tv/js/embed/v1.js"></script>
        ...
    </head>
    

    add this to component ngOninit method

          ngOnInit() {
            var options = {
                width: <width>,
                height: <height>,
                channel: "<channel ID>",
                video: "<video ID>",
                collection: "<collection ID>",
              };
              var player = new Twitch.Player("<player div ID>", options);
              player.setVolume(0.5);
           }
    

    Component template

        <div id="<player div ID>"></div>
    

    You may find another solution like angular package for twitch can be more cleaner way

    Updated

    typescript will give an error like [ts] Cannot find name 'Twitch'. [2304] some library has type definition files but in our case if you use Twitch object in this file only you can add this statement to tell typescript about the Twitch object

    declare const Twitch: any;
    

    if you want to use Twitch on multiple components

    src/global.d.ts

     declare const Twitch: any;
    

    final recommendation

    install npm i twitch-js and import Twitch object like this

    import Twitch from 'twitch-js'

    this will be bundled by webpack, so you don't need to add any script tag in the html.

    twitch-devs