Capturing Camera using Angular 5

HTML 5 has very useful <video> control to play video. All you need to do is set it’s “src” property. You can configure <video> using various properties and API which can be called via JavaScript. But how about Angular 5?

Well in Angular, it is also simple to work with camera. Trick here is to use HTML local alias (#) on <video> tag and access it inside app.component.ts using @ViewChild() decorator.

Before we proceed further, play with live demo and get an understanding of what we are going to discuss in this story.

Here is the HTML gist. Notice <video> tag has “videoElement” alias.

@ViewChild() decorator (exported from @angular/core) accepts a string parameter which should be HTML local alias prefixed with hash character (#) in this case ‘videoElement’. This decorator will link HTML <video> tag with member variable of AppComponent class. Using populated member variable, now you can access all native HTML properties and methods using ‘nativeElement’ property of ‘videoElement’.

Check out the code.

Accessing Camera

navigator is built in object (similar to window) and expose camera, microphone and other native browser settings via APIs.

Note that Google Chrome, Mozilla Firefox, Microsoft Edge have different settings for navigator. Hence we need to set specific media type while initializing camera (line number 11–14 in below gist).

Line 16–19 returns a promise accepting configuration JSON object where you can specify settings like enable audio, video, set height and width etc.

On “Play” button click, we are starting only video where as on click of “Play with Sound” button we are starting video plus audio. Observe “initCamera()” function parameter for both button click handler.

Explore MDN for detailed configuration about “getUserMedia()”.

Controlling video

Using native <video> referenced member variable, we can set properties can call methods of <video> tag.

ToggleControl bar:

<video> tag has an attribute called ‘control’. If set to true, video tag will show control bar with seek bar, full screen option, pause etc. We can set this property on button click.

Pause video:

Just call pause() method of video and video shall get paused.

Resume video:

Calling play() method shall resume paused video.

So, isn’t it easy and fun working with camera?

You can explore complete source code here:

Cheers!

Cloud Solution Architect | Author | Full Stack Developer | https://www.linkedin.com/in/balram-chavan | https://www.hiretheauthor.com/balramchavan

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