abhijeetwebdev
abhijeetwebdev

Reputation: 396

How to get height and width of the video in Angular 2, TypeScript

I need to check if the video is portrait or landscape, for that I am trying to get the height, width of the video this way,

import { Component, OnInit, AfterViewInit } from '@angular/core';

@Component({
  selector: 'app-videplayer',
  template: `<video id="singleVideo">
                <source src="/assets/videoname.mp4" type="video/mp4">
            </video>`
})
export class VideplayerComponent implements OnInit, AfterViewInit {
  constructor() {}

  ngOnInit() {
  }

  ngAfterViewInit() {
    const videoElem: HTMLVideoElement = <HTMLVideoElement>document.getElementById('singleVideo');
    const vidH = videoElem.videoHeight;
    const vidW = videoElem.videoWidth;
    console.log(vidH, vidW); // this returns: 0, 0
  }

}

I tried getting the height, width of the video within constructor, ngOnInit and ngAfterViewInit functions but I'm a getting 0 height and with all the time.

Upvotes: 0

Views: 2103

Answers (2)

Jigar
Jigar

Reputation: 23

Try with offsetHeight and offsetWidth as below:

const vidH = videoElem.offsetHeight;    
const vidW = videoElem.offsetWidth;

And, if it still does not work then try with some timeout in ngAfterViewInit() as below:

ngAfterViewInit() {
    setTimeout(function () {
       const videoElem: HTMLVideoElement = <HTMLVideoElement>document.getElementById('singleVideo');
       const vidH = videoElem.offsetHeight;
       const vidW = videoElem.offsetWidth;
       console.log(vidH, vidW); // this returns: 0, 0
    }, 500);
}

Upvotes: 2

C3roe
C3roe

Reputation: 96306

From MDN, on the videoHeight/-Width properties:

If the element's ready state is HAVE_NOTHING, the value is 0

https://developer.mozilla.org/en-US/docs/Web/API/HTMLVideoElement

I think your best option here is to set up a readystatechange event handler, and then inside that check if the state is > 0 (HAVE_NOTHING), and then read the dimensions. (Next readyState would be 1/HAVE_METADATA, and from there on the video dimensions should be available.)

https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/readyState

Upvotes: 1

Related Questions