Search code examples
angularvideo.js

Setup video.js on angular2


I am using video.js to work on my angular2 vidoes but couldn't make it work. I am using video.js CDN in my index file.

<link href="https://vjs.zencdn.net/5.11/video-js.min.css" rel="stylesheet">
<script src="https://vjs.zencdn.net/5.11/video.min.js"></script>

I have a template file

<video *ngIf="videoUrl" id="{{id}}"
  class="video-js vjs-big-play-centered"
  controls
  preload="auto"
>
  <source src="{{listing.url}}" type="video/mp4">
</video>

And component with video.js code inside ngAfterViewInit

export class ListingComponent implements AfterViewInit, OnInit, OnDestroy {

id: string;

  ngAfterViewInit() {
    videojs(document.getElementById(this.id), {}, function() {
      // Player (this) is initialized and ready.

    });
  }

}

The problem is, it shows error : "Cannot find name 'videojs'." that is inside ngAfterViewInit

I also tried installing video.js via npm and import {videojs} from 'video.js but that didn't work either.

Someone please help me out how to make video.js work with angular2. Thanks in advance


Solution

  • First your are not initializing the videojs. So its showing the videojs undefined.

    just find this below code:

    declare var videojs: any;
    
    export class ListingComponent implements AfterViewInit, OnInit, OnDestroy {
    
      id: string;
      private videoJSplayer: any;
    
      constructor() {}
    
      ngAfterViewInit() {
        this.videoJSplayer = videojs(document.getElementById('video_player_id'), {}, function() {
          this.play();
        });
      }
    
      ngOnDestroy() {
        this.videoJSplayer.dispose();
      }
    }
    

    html:

     <video 
       *ngIf="videoUrl" 
       id="video_player_id"
       class="video-js vjs-big-play-centered"
       controls 
       preload="auto">
       <source src="{{listing.url}}" type="video/mp4">
     </video> 
    

    check this link: videojs plunker plunker with answered