Back-end9 minute read

Building an Angular Video Player With Videogular

Video accounts for more than three quarters of all bandwidth used today. That’s why developers need a solid, extensible, and advanced media framework that doesn’t come with a steep learning curve.

In this tutorial, Toptal Freelance Software Engineer Raul Jimenez will introduce you to one such framework – Videogular. If you need to harness the power of Angular for HTML5 video, look no further.


Toptalauthors are vetted experts in their fields and write on topics in which they have demonstrated experience. All of our content is peer reviewed and validated by Toptal experts in the same field.

Video accounts for more than three quarters of all bandwidth used today. That’s why developers need a solid, extensible, and advanced media framework that doesn’t come with a steep learning curve.

In this tutorial, Toptal Freelance Software Engineer Raul Jimenez will introduce you to one such framework – Videogular. If you need to harness the power of Angular for HTML5 video, look no further.


Toptalauthors are vetted experts in their fields and write on topics in which they have demonstrated experience. All of our content is peer reviewed and validated by Toptal experts in the same field.
Raul Jimenez Herrando
Verified Expert in Engineering

A JS developer since 2001, Raul is the creator of Videogular and an expert in Angular, high-performance web apps, and video streaming.

PREVIOUSLY AT

Ogilvy Interactive
Share
The Videogular project is supported by Toptal Open Source Grants. Toptal Open Source Grants supports members of the Toptal network pursuing Open Source projects.

As one of the first Open Source Grants recipients, Raul Jimenez Herrando is adding new features, fixing bugs, and writing documentation for the Videogular project. To learn more about Toptal Open Source Grants, email opensource@toptal.com.

According to online traffic statistics, video is taking over control of the web. The good old TV is dying and companies are moving fast to dominate a market that will represent the 80% of online traffic by 2019 .

Many media providers and products rely on HTML5 video support:

  • Youtube: HTML5 video and social sharing platform
  • Netflix: HTML5 video content provider
  • JWPlayer: HTML5 video service and streaming provider
  • Brightcove: HTML5 video service and streaming provider
  • Kaltura: HTML5 video service and streaming provider
  • Video.js: HTML5 video player
  • Flowplayer: HTML5 video player and streaming provider

The developer community needs a solid, extensible, and advanced media framework (not just an HTML5 video player) to face the new challenges that lay ahead. In this article, I want to introduce one such framework: Videogular.

What Is Videogular?

As the name suggests, Videogular is a media framework written in Angular 2+. With Videogular, you can play HTML5 video, audio, or any other content that you want. There is an implementation for Angular 1.X (a.k.a AngularJS), but in this article we will talk only about the current Angular 2+ version.

So, the next question that probably is crossing your mind is: Why use Angular for video?

Cover illustration: Building an Angular video player

Well, there are a number of good reasons for choosing a specific framework to create a video library.

  • Ease of contribution: Because Videogular is based on Angular, a popular framework with a very active community, it’s very easy for other people to start contributing by creating plugins or fixing bugs.
  • Web Components: No need to write JavaScript to create and style your own player. You can write HTML and CSS code.
  • TypeScript: Angular is a typed framework, as well as all the libraries around it. Having a strongly typed ecosystem allows us to detect bugs and architecture problems before it’s too late.
  • Speed: All the latest popular frameworks are blazing fast, including Angular.

Additionally, we have some other cool features like RxJS, AOT (ahead-of-time compilation), the Angular CLI, and more.

How Does Videogular Work?

I like to say that Videogular is more of a media framework than just an HTML5 video player. The most relevant feature and difference between other video players is that you write tags to set up your player instead of JavaScript.

This is how most video players work right now:

<video class="library" controls preload="auto" data-config="some-js-object-here">
  <source src="video-url.mp4" type='video/mp4'>
</video>
 
<script src="video-library.js"></script>

And this is what Videogular implementation looks like:

<vg-player>
   <vg-overlay-play></vg-overlay-play>
   <vg-buffering></vg-buffering>
 
   <vg-controls>
       <vg-play-pause></vg-play-pause>
       <vg-time-display vgProperty="current" vgFormat="mm:ss"></vg-time-display>
 
       <vg-scrub-bar>
          <vg-scrub-bar-current-time></vg-scrub-bar-current-time>
          <vg-scrub-bar-buffering-time></vg-scrub-bar-buffering-time>
       </vg-scrub-bar>
 
       <vg-time-display vgProperty="total" vgFormat="mm:ss"></vg-time-display>
 
       <vg-track-selector></vg-track-selector>
       <vg-mute></vg-mute>
       <vg-volume></vg-volume>
 
       <vg-fullscreen></vg-fullscreen>
   </vg-controls>
 
   <video #myMedia [vgMedia]="myMedia" id="myVideo" preload="auto" crossorigin>
       <source src="video-url.mp4" type='video/mp4'>
       <track kind="subtitles" label="English" src="assets/subs/pale-blue-dot.vtt" srclang="en" default>
       <track kind="subtitles" label="Español" src="assets/subs/pale-blue-dot-es.vtt" srclang="es">
   </video>
</vg-player>

The good thing about Videogular is that, with just a quick look to the HTML code, you know how this player works, which controls are available, and how to modify it to remove, for example, the tracks and the track selector.

But this is not the only advantage we can benefit from when building an Angular video player. Think of big development teams where HTML/CSS designers and JavaScript developers work together on the same code base. Because we’re using custom elements, designers can start working by applying styles and animations without the need to learn a new library or even JavaScript/TypeScript.

Also, Videogular provides much more powerful capabilities than just writing a plain Angular video player, like automatic synchronization between several media files, or the ability to play not only video/audio, but just about any content that has a beginning and an end.

To see how easy is to create a rich, interactive app with Videogular, we’re going to create a video playlist with synchronized metadata.

How to Install Videogular

In this example, we will have a list of videos and a related excerpt from Wikipedia, just in case the user needs to have more information about the video.

All the code is available on our Videogular Showroom GitHub repo and it’s published as a GitHub page.

Videogular installation should be a straighforward affair for any skilled Angular developer. On the other hand, if you’re just getting started in Angular, you should check out this quick guide to making your first Angular app.

If you have not installed Node.js yet, go to the Node.js official website and install it. This is the only server we need to develop with Angular, and we need it to install dependencies via NPM. You just need to be sure to install Node.js 6.9.0 or higher and NPM 3.0.0 or higher.

The first thing we need to do is to install the Angular CLI. The Angular CLI is a must-have tool for any Angular developer, since it provides easy scaffolding, testing, development servers, and productions builds. Even more importantly, it follows a convention that any other Angular developer can understand.

Install the Angular CLI globally via NPM:

npm install -g @angular/cli

And let’s create our first project with support for SASS:

ng new smart-video-playlist --style=scss

This should create a sample project for you. If you want to start developing and watching the results at the same time, you can run npm run start and open [http://localhost:4200](http://localhost:4200). The Angular CLI will run a Node.js development server with live reloading and all the cool features that we as developers love.

Now you can install the videogular2 library and core-js typings:

npm install videogular2 --save
npm install @types/core-js --save-dev

Creating an Angular video player

If you want to, you can use the official Videogular font to set icons on your buttons and controls. To do that you need to add CSS to your .angular-cli.json file available on the root of your project.

{
   ...
   "apps": [
       {
           ...
           "styles": [
               "../node_modules/videogular2/fonts/videogular.css",
               "styles.scss"
           ],
           ...
       }
   ],
   ...
}

If you want to set your own font and styles, you can set your custom CSS here or inside styles.scss.

To start using Videogular in your project, you have to add the Videogular module to your application module.

Open src/app/app.module.ts and remove the FormsModule and the HttpModule; we will not need them for this demo. This is how your app.module.ts file should like:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
 
import { AppComponent } from './app.component';
import { VgCoreModule } from 'videogular2/core';
import { VgControlsModule } from 'videogular2/controls';
 
@NgModule({
   declarations: [
       AppComponent
   ],
   imports: [
       BrowserModule,
       VgCoreModule,
       VgControlsModule
   ],
   providers: [],
   bootstrap: [ AppComponent ]
})
export class AppModule {
}

With everything set up, we just need to write our HTML code!

<vg-player>
   <vg-controls>
       <vg-play-pause></vg-play-pause>
       <vg-playback-button></vg-playback-button>
 
       <vg-time-display vgProperty="current" vgFormat="mm:ss"></vg-time-display>
 
       <vg-scrub-bar>
           <vg-scrub-bar-current-time></vg-scrub-bar-current-time>
           <vg-scrub-bar-buffering-time></vg-scrub-bar-buffering-time>
       </vg-scrub-bar>
 
       <vg-time-display vgProperty="total" vgFormat="mm:ss"></vg-time-display>
 
       <vg-mute></vg-mute>
       <vg-volume></vg-volume>
 
       <vg-fullscreen></vg-fullscreen>
   </vg-controls>
 
   <video #media [vgMedia]="media" id="singleVideo" preload="auto" crossorigin>
       <source src="http://static.videogular.com/assets/videos/videogular.mp4" type="video/mp4">
   </video>
</vg-player>

Now you can run the server and enjoy your first video app powered by Angular and Videogular.

npm run start

Building a Media Playlist in Angular

To list our videos, we will create a simple array with all the options. Just keep in mind that you can load this list via a REST service with Angular’s HttpModule, but for the sake of simplicity, we will do this hard-coded in this demo.

Open app.component.ts and add this array of videos and its interface:

import { Component } from '@angular/core';
 
export interface IMedia {
   title: string;
   src: string;
   type: string;
}
 
@Component({
   selector: 'app-root',
   templateUrl: './app.component.html',
   styleUrls: [ './app.component.scss' ]
})
export class AppComponent {
   playlist: Array<IMedia> = [
       {
           title: 'Pale Blue Dot',
           src: 'http://static.videogular.com/assets/videos/videogular.mp4',
           type: 'video/mp4'
       },
       {
           title: 'Big Buck Bunny',
           src: 'http://static.videogular.com/assets/videos/big_buck_bunny_720p_h264.mov',
           type: 'video/mp4'
       },
       {
           title: 'Elephants Dream',
           src: 'http://static.videogular.com/assets/videos/elephants-dream.mp4',
           type: 'video/mp4'
       }
   ];
}

Now we’re ready to add the playlist below our player in the HTML file:

<ul>
   <li *ngFor="let item of playlist; let $index = index"
       (click)="onClickPlaylistItem(item, $index)"
       [class.selected]="item === currentItem">
       {{ item.title }}
   </li>
</ul>

Let’s add some styles for the selected class and the hover effect:

ul {
   list-style-type: none;
   margin: 0;
   padding: 0;
   font-family: sans-serif;
 
   li {
       padding: 10px;
       cursor: pointer;
 
       &.selected {
           background-color: #dddddd;
       }
 
       &:hover {
           background-color: #cce6ee;
       }
   }
}

The method onClickPlaylistItem will set the media to play on our Videogular player. Let’s go now to app.component.ts to add the method:

// ...
export class AppComponent {
   // ...
 
    currentIndex = 0;
    currentItem: IMedia = this.playlist[ this.currentIndex ];
 
    onClickPlaylistItem(item: IMedia) {
        this.currentIndex = index;
        this.currentItem = item;
    }
}

The property currentIndex will be used later to identify the current item and its position in the playlist. This is important to do infinite loop playlists and update the currentIndex when the user clicks on an item of the playlist.

Finally, we only have to modify the video element to set the source from the currentItem property handled by the playlist. We will create for this a simple binding to the src property of the HTML5 video element:

<video #media
      [vgMedia]="media"
      [src]="currentItem.src"
      id="singleVideo"
      preload="auto"
      crossorigin>
</video>

Now we can test our playlist and see how it works. The first video is loaded at the beginning and we can change between videos, so everything’s fine! But we can make some tweaks and improve the experience by switching automatically between videos when a video is completed, and adding better overall management of the player state.

To do this we will need the Videogular API, a global service available on every Videogular instance to handle the state and listen for events.

Using VgAPI to handle states

Our media playlist is right now 100% functional, but we can improve the user experience by autoplaying videos when a new item is selected or when a video is completed.

Videogular exposes an API to control and listen for changes for each VgMedia instance inside the VgPlayer component. Actually, all Videogular modules are based in this public API, so you can create your own modules for your customers or contribute to the community by releasing them as open source.

To use the Videogular API, you just need to listen for the onPlayerReady event fired by the VgPlayer component:

<vg-player (onPlayerReady)="onPlayerReady($event)">
// ...

When the player is initialized, you can save the API and start listening for the events dispatched by the video tag:

export class AppComponent {
   // ...
 
   onPlayerReady(api: VgAPI) {
       this.api = api;
   }
}

The Videogular API is based on RxJS, so you can subscribe to Observables and react in consequence. To autoplay the videos, we need to listen for the loadedmetadata event.

Let’s add a new Subscription to play the video when the metadata is loaded:

export class AppComponent {
   // ...
 
   onPlayerReady(api: VgAPI) {
       this.api = api;
       this.api.getDefaultMedia().subscriptions.loadedMetadata.subscribe(
           this.playVideo.bind(this)
       );
   }
 
   playVideo() {
      this.api.play();
   }
 
   // ...
}

That was easy; we simply play the video via the VgAPI when the loadedMetadata observable is fired.

Do you remember the currentIndex property? Now is the moment to use it so we can move to the next video when the current video is completed:

// ...
export class AppComponent {
   // ... 
   onPlayerReady(api: VgAPI) {
       this.api = api;
       this.api.getDefaultMedia().subscriptions.loadedMetadata.subscribe(
          this.playVideo.bind(this)
       );
       this.api.getDefaultMedia().subscriptions.ended.subscribe(
          this.nextVideo.bind(this)
       );
   }
 
   nextVideo() {
       this.currentIndex++;
 
       if (this.currentIndex === this.playlist.length) {
           this.currentIndex = 0;
       }
 
       this.currentItem = this.playlist[ this.currentIndex ];
   }
 
   // ...
}

With this method, we can handle when the ended event is fired by the video tag and then move to the next video. We also added a small control to do an infinite loop when we reach the end of the playlist by setting currentIndex = 0; so we can move back to the first item. Finally we set the currentItem that will update our Angular bindings in the UI.

As you can see, we’re not playing the video here; that’s because we handle that with the loadedMetadata observable. When we update the currentItem inside nextVideo(), a new video is loaded and that triggers the loadedMetadata observable.

This makes our code easier to read and harder to break! Observables are awesome right?

What’s next?

From here, we could add some HTML5 video controls to remove autoplay or the infinite loop, inject advertisements, or synchronize information.

In this demo, we just scratched the surface of what’s possible to do with Videogular. The API is capable of managing several media files at the same time, we have modules for streaming and advertisement, and you can even create a media player to play animations, routes in a map, and much more.

Videogular is released under an MIT license and is an open-source project available on GitHub. Everybody is welcome to create a pull request, submit an issue, write documentation, and contribute to the community.

Understanding the basics

  • Who created AngularJS?

    Angular was created and is currently maintained by Google, though as an Open Source framework, its community is supporting it a lot with external contributions, and some of these has been added to the core, like Angular Universal or the Angular CLI.

  • What is an HTML5 video?

    HTML5 video is a native browser API to play video and audio files directly in the browser without the need for plugins like Flash or Silverlight. Video on the web has been evolved rapidly and right now is capable of doing anything that you can do with plugins.

  • What is Videogular?

    Videogular is a powerful media framework powered by Angular. It’s particularly useful for the creation of HTML5 website video players.

  • What is AngularJS/Angular 2+?

    Angular is a JavaScript framework developed by Google. The community usually talks about AngularJS when they are referring to the Angular v1.X version, and just Angular when they talk about Angular v2.X and above.

Hire a Toptal expert on this topic.
Hire Now
Raul Jimenez Herrando

Raul Jimenez Herrando

Verified Expert in Engineering

Barcelona, Spain

Member since September 23, 2015

About the author

A JS developer since 2001, Raul is the creator of Videogular and an expert in Angular, high-performance web apps, and video streaming.

authors are vetted experts in their fields and write on topics in which they have demonstrated experience. All of our content is peer reviewed and validated by Toptal experts in the same field.

PREVIOUSLY AT

Ogilvy Interactive

World-class articles, delivered weekly.

By entering your email, you are agreeing to our privacy policy.

World-class articles, delivered weekly.

By entering your email, you are agreeing to our privacy policy.

Join the Toptal® community.