Discovering the dimensions of a video in Angular 2 using TypeScript

To determine whether the video is portrait or landscape, I am attempting to retrieve the height and width of the video using the following method:

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

@Component({
  selector: 'app-videoplayer',
  template: `<video id="singleVideo">
                <source src="/assets/videoname.mp4" type="video/mp4">
            </video>`
})
export class VideoplayerComponent 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
  }

}

Despite my efforts in trying to obtain the video's height and width within the constructor, ngOnInit, and ngAfterViewInit functions, I consistently receive 0 values for both dimensions.

Answer №1

Experiment with using offsetHeight and offsetWidth in the following manner:

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

If this approach still does not yield results, consider adding a delay using timeout within the ngAfterViewInit() method like so:

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

Answer №2

According to information from MDN concerning the videoHeight/-Width properties:

If the element's state is HAVE_NOTHING, then the value will be 0

Visit this link for more details.

In my opinion, the best approach would be to establish a readystatechange event handler. Within that, you can verify if the state is > 0 (HAVE_NOTHING), and subsequently retrieve the dimensions. Once the readyState progresses to 1/HAVE_METADATA, the video dimensions should become accessible.

Click here for further insights.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Pass the code from the webpage to the PHP script

On my website, I have implemented a feature using JavaScript that dynamically changes the page content. Now, I am looking for a way to send this updated content to a PHP script. How can I achieve this functionality? ...

jquery accordion failing to display content

Upon navigating to my website and accessing the webpage featuring an accordion, the accordion successfully appears and hides after 1500ms as intended. However, when attempting to reveal the text by clicking on the headings, nothing happens. The heading sim ...

Incorporate a smooth transition effect to a dynamically resizing div button

In my current setup, I have 3 buttons that can toggle between different visible divs. In the future, I may add more buttons to switch between additional divs. At the moment, the first div is active (display set to block), while all other divs are hidden ( ...

How can I create a dashed border for a pie chart using highcharts?

Is there a way to change the default solid border of a pie highchart to dashed? This modification is only necessary for pies without data or with negative data values. Perhaps it's possible to redraw the SVG of the border, like in this example: https: ...

Prevent any unauthorized modifications to the ID within the URL by implementing appropriate security measures

I am currently developing an application using React and Express. The URL structure is similar to this: /dashboard?matchID=2252309. Users should only have access to this specific URL, and modifying the match ID should not allow them to view the page. Is ...

Implementing conditional data binding in Angular with ngIf directive

I've been struggling to showcase recipes from a specific food category. I'm attempting to iterate through an array of recipes within a parent component. <div class="row"> <div class="col-xs-8" *ngIf="{{ recipe.category }} === mexican" ...

All the details from this run are available in the npm run dev log on Ubuntu

Good day! I've been working on deploying a page built in vue.js, and after uploading all the files successfully, I encountered an issue when trying to run "npm run dev." No matter what I try, including re-installing npm dependencies and starting from ...

Is fs-extra the best tool for working with a .bundle file?

I am attempting to determine whether a specific folder in my project includes a .bundle file and, if it does, relocate it to another location. If the file is not found, I will use a default option instead. The problem I'm encountering is that I am una ...

angular 6 httpclient include login information in the URL

When attempting to make a HTTP GET request from an Angular 6 project to a CouchDB, I encountered a 401 Error "You are not authorized to access this db." despite passing the credentials in the URL. Below is the code snippet: var url = "http://user:passwor ...

Identifying when a user closes a tab or browser to trigger a logout in JavaScript with Vue.js using the Quasar framework

Is there a way to trigger the logout function only when the tab or browser is closed, and not when the page is refreshed? I attempted the following code example, which successfully triggers the logout on tab close but also logs out when the page is ref ...

The 'pipe' property is not found on the 'Promise<HTTPResponse>' data type

Is there a way to fetch a list of products using an http call, apply pipe and map functions to the result, and then return it to the subscribed function? I am currently utilizing the ionic cordova advanced http plugin for SSL pinning in my requests. Howeve ...

Sending a notification alert directly to the client's web browser

My goal is to develop an application that allows Super users to notify other users by providing access to content, such as a PDF file, when they click on a link. For example, in the scenario where a teacher wants to share a PDF with students, this applica ...

After creating a new Packery using AngularJS, the getElementById function may return null

Alright, so I've got this HTML markup: <button ng-click="create()">create list</button> Every time I click it, I create a new list using the Packery jQuery plugin. app.directive('packery', ['$compile', function($com ...

Discovering the permissible array values from numerous arrays inside an object using TypeScript

I have an object with multiple arrays of strings (hardcoded). I want to specify that only strings from that object are allowed in another empty array. In a simple non-nested scenario, I'm achieving this with typeof someArray[number][]. So, I hoped to ...

Unexpected token < error encountered during parsing in jQuery Ajax long polling append

How can I create a real-time ticker similar to Facebook using Jquery Ajax long poll and PHP? I encountered an error in my script that displays "error parsererror (SyntaxError: Unexpected token <)". What could be causing this error in my code? Here is ...

Utilizing a single code base for both Web development with Angular 4 and Mobile app development with Ionic 3

I'm interested in finding out if I can utilize the same code base for both my Angular 4 web application and an Ionic 3 mobile application that I need to develop. As someone who is new to Ionic 3, I've been exploring the documentation and discove ...

Using Observables in Angular 2 to send polling requests

I have the following AngularJS 2 code snippet for polling using GET requests: makeHtpGetRequest(){ let url ="http://bento/supervisor/info"; return Observable.interval(2000) .map(res => res.json()) //Error here ...

Issue with mailgun causing email to not send and returning undefined data

Trying to set up a basic email confirmation process for signups using Angular 4, Node.js, mailgun-js and mailgun, but encountering issues with the mailgun send method. mailgun.messages().send(data, function(error, body) { console.log(body); }) ...

The Vue component should trigger the display of data in a Bootstrap modal based on the row of the button that was

Here is a sample code snippet demonstrating how data is fetched from the database: <table class="table table-bordered"> <thead> <tr><th>User ID</th><th>Account Number</th><th>Accou ...

Form with several file selection points

I am working on an application that features a dynamic form capable of uploading files to different individuals simultaneously. Each person is assigned a unique input file and has the option to add up to 2 additional dynamic inputs. <div id="InputsWra ...