Video.js and Angular integration

Here’s a basic Angular player implementation.

It just instantiates the Video.js player on OnInit and destroys it on OnDestroy.

  1. // vjs-player.component.ts
  2. import { Component, ElementRef, Input, OnDestroy, OnInit, ViewChild, ViewEncapsulation } from '@angular/core';
  3. import videojs from 'video.js';
  4. @Component({
  5. selector: 'app-vjs-player',
  6. template: `
  7. <video #target class="video-js" controls muted playsinline preload="none"></video>
  8. `,
  9. styleUrls: [
  10. './vjs-player.component.css'
  11. ],
  12. encapsulation: ViewEncapsulation.None,
  13. })
  14. export class VjsPlayerComponent implements OnInit, OnDestroy {
  15. @ViewChild('target', {static: true}) target: ElementRef;
  16. // see options: https://github.com/videojs/video.js/blob/maintutorial-options.html
  17. @Input() options: {
  18. fluid: boolean,
  19. aspectRatio: string,
  20. autoplay: boolean,
  21. sources: {
  22. src: string,
  23. type: string,
  24. }[],
  25. };
  26. player: videojs.Player;
  27. constructor(
  28. private elementRef: ElementRef,
  29. ) { }
  30. ngOnInit() {
  31. // instantiate Video.js
  32. this.player = videojs(this.target.nativeElement, this.options, function onPlayerReady() {
  33. console.log('onPlayerReady', this);
  34. });
  35. }
  36. ngOnDestroy() {
  37. // destroy player
  38. if (this.player) {
  39. this.player.dispose();
  40. }
  41. }
  42. }

Don’t forget to include the Video.js CSS, located at video.js/dist/video-js.css.

  1. /* vjs-player.component.css */
  2. @import '~video.js/dist/video-js.css';

You can then use it like this.

  1. <app-vjs-player [options]="{ autoplay: true, controls: true, sources: [{ src: '/path/to/video.mp4', type: 'video/mp4' }]}"></app-vjs-player>