How To Use <video> In Angular?

Attribute Directives

Angular provides three types of directives, but for this article, we are going to focus on attribute ones. From Angular’s documentation:

HTMLVideoDirective

The first thing that we need is to be able to interact with the HTMLVideoElement in order to connect the data received from the camera and play it in an easy way. This straightforward directive comes to the rescue and provides a typed HTMLVideoElement element.

MediaStreamDirective

Now that we have typed-safe access to the camera using an Angular mechanism, it’s time to extend the previous directive in order to achieve our goal. As you can see in the selector definition, we are going to prevent the use of this directive only to <video> elements.

Playing, Pausing and Stopping Video

For playing, pausing and stopping video is necessary to interact with the MediaStream API. The mechanism provided by this API to retrieve the element is called getUserMedia(). As part of the result we are going to be able to interact with every track requested, that is video, audio or both.

Taking a Picture

For taking a picture of the displayed video in a given moment we are going to project the content of the <video> into a canvas. The size will be the same as the <video> node (or the ones provided by the consumer). After that, it is just a matter of transforming the information to data URI using toDataURL().

Recording a Video

Recording a part of the streaming video is tricky because for this purpose, we will be using a native API (MediaRecorder) that unfortunately is not available in any browser (at the moment of writing this article).

Using it

This directive can be used in your component by just adding a small piece of code to both HTML and typescript files.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store