Unable to set dimensions for an image within an input field using TypeScript

My goal is to retrieve and assign the height and width of an image to hidden text inputs in HTML, as shown below:

The purpose is to obtain the height and width for validation.

HTML:

<input type="file" class="file" #introIcon id="uploadBtn" (change)="onFileChange($event)" name="browseIcon">
<input type="number" class="hidden" id="imgWidth" value="">
<input type="number" class="hidden" id="imgHeight" value="">

TS:

onFileChange(event) {
      if (event.target.files.length > 0) {
        const file = event.target.files[0];
        this.fileName = file.name;
        this.fileType = file.type;
        if(this.fileType == 'image/png' || this.fileType == 'image/jpeg' || this.fileType == 'image/PNG' || this.fileType == 'image/JPEG') {
          const reader = new FileReader();
          reader.onload = e => {
            this.url = reader.result;
            var imageObj = new Image();
            imageObj.src = this.url;
            imageObj.onload = function () {
              console.log('p1:', imageObj.height);
              console.log('p2:', imageObj.width);
              // (<HTMLSelectElement>document.getElementById('imgWidth')).value = imageObj.width;  <-- here getting error
              // (<HTMLSelectElement>document.getElementById('imgHeight')).value = imageObj.height; <-- here getting error
            };
          }
          reader.readAsDataURL(file);
          let fName = (<HTMLSelectElement>document.getElementById('uploadFile')).value;
          fName = this.fileName;
          this.uploadFileName.nativeElement.value = fName;
          this.form.get('browseIcon').setValue(file);
        } else {
          // error
        }
      }
    }

Error occurs in the following lines:

(<HTMLSelectElement>document.getElementById('imgWidth')).value = imageObj.width;  
(<HTMLSelectElement>document.getElementById('imgHeight')).value = imageObj.height;

Type 'number' is not assignable to type 'string'

I have already searched on Google but none of the solutions provided worked!

Attempted solution: Type 'number' is not assignable to type 'string'

Answer №1

What do you think of this solution?

(<HTMLSelectElement>document.getElementById('imgWidth')).value = imageObj.width.toString();  
(<HTMLSelectElement>document.getElementById('imgHeight')).value = imageObj.height.toString();

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

Error encountered in Snap SVG combined with Typescript and Webpack: "Encountered the error 'Cannot read property 'on' of undefined'"

I am currently working on an Angular 4 app that utilizes Snap SVG, but I keep encountering the frustrating webpack issue "Cannot read property 'on' of undefined". One solution I found is to use snapsvg-cjs, however, this means losing out on the ...

When incorporating pinia with Vue, encountering an error with the decorator that says "Error: Unable to access 'useCoreStore' before initialization" may happen

While implementing the vue-facing decorator in my current project, I encountered an issue with setting up pinia. The structure of my component resembles the example provided here: I have verified that decorators like @Setup are functioning correctly, ind ...

When working in a Typescript Vue2 component, accessing the $store through typing this.$store

After setting up a Vue2+Vuex typescript app from scratch using the @vue/cli, I am facing an issue with the type declarations of this.$store.state within my components. How can I ensure that references to this.$store are correctly typed as declared by the ...

Using SVG files in NextJS

I'm encountering an issue while trying to import an SVG file in a NextJS project. The error message I keep getting is: ./assets/aboutimg.svg 1:0 Module parse failed: Unexpected token (1:0) You may need an appropriate loader to handle this file type, ...

Is it possible to pass the index variable of a for loop to a different function?

As a current bootcamp student, I have a question about passing the index of a for loop to another function. Specifically, I am trying to fetch data from an API (which provides me with a random cryptocurrency from an array) 4 times and then pass that data ...

Leveraging private members in Typescript with Module Augmentation

Recently, I delved into the concept of Module Augmentation in Typescript. My goal was to create a module that could inject a method into an object prototype (specifically a class) from another module upon import. Here is the structure of my folders: . ├ ...

MongoDB function failing to properly return an array

I am currently exploring an efficient method to determine if each string within an array exists on MongoDB. The specific field to be queried is the 'name' field. However, I am encountering an issue when using the function below as it returns und ...

How can I create a parent div with cursor-pointer and apply inline styling to make all child elements

Is there a way to apply the cursor-pointer style to an entire div with inline CSS without it affecting just the white space around the child elements? I have tried using position and z-index without success. I am unable to use an external stylesheet for t ...

Serialize a series of select boxes to optimize for AJAX POST requests

To better explain my issue, let's consider a simple example: Imagine I have a form that collects information about a user: <form action="#" method="post" id="myform"> <input type="text" name="fname" /> <input type="text" name= ...

Data vanished from the input field values

Having an issue with displaying an HTML table inside a .cshtml file. When I hardcode values, the table appears as expected. However, when I attempt to populate it using a foreach loop, the table disappears. <script> var nTable = ""; $(docu ...

The uploaded files are not supported due to a media type error (415)

Although I found a similar query, it didn't provide a solution to the error I am encountering. Below is the PUT action in my API's Controller, which functions correctly in Swagger: [HttpPut("{id}/upload")] public async Task<IActionResult> ...

React component performing AJAX requests

I have a React component that utilizes highcharts-react to display a chart fetched from an API using some of its state properties. export default class CandlestickChart extends React.Component { constructor (props) { super(props); this ...

Mastering Props Typing in React Using TypeScript

Currently, I am faced with the task of defining the following: interface MyCompProps { someAttr: number } Instead of having to explicitly list all the aria-* attributes I need upfront, I would like to simply use aria- and other normal HTML attributes ...

Angular 5+ does not have any compatible call signatures for Type Search

Utilizing an addItem function that I found on this site, I encountered the following error message: Error TS2349 (TS) Cannot invoke an expression whose type lacks a call signature. Type 'Search' has no compatible call signatures. Definition o ...

Error occurred after attempting to make a GET request

What I aim to achieve: I need to send two parameters from the front-end to the back-end. This is the code snippet: In TypeScript file: activeFromActiveToQuery(req?: any): Observable<ResponseWrapper>{ const options = createRequestOption(req) ...

Transform the jQuery each method into vanilla JavaScript

I have a script that displays a dropdown in a select box. The current script I am using is as follows: jQuery.each( dslr, function( index, dslrgp) { var aslrp= dslrgp.aslrp; jQuery.each( aslrp, function(index2, pslrp) { var found = 0; ...

The action of adding an item to the cart will result in all counters

I am facing an issue where the counters of all options in the cart increase simultaneously when I add an option. I initially attempted to solve this using Vuex, but my lack of experience led me to take a simpler approach. How can I prevent all option count ...

Issues with Alignment of Navbar Elements in Bootstrap 3

When I test my website locally, the elements are aligned correctly as expected. However, when I view it on my live webpage, the elements are all left-aligned. I've attempted a solution from this source, but the issue persists. What confuses me is why ...

Encountered a VUE error stating "Cannot use 'in' operator to search for 'path' in undefined". This issue led to an infinite loop, prompting me to search for solutions on StackOverflow and other similar forums. More details can be found

I am currently using this demo for learning purposes. If you want to see the full code, you can visit my GitHub repository here: https://github.com/tNhanDerivative/nhanStore_frontEnd and access my domain: vuestore.nhan-thenoobmaster.com. The error I am exp ...

The node.js application was unable to locate the '../HMS/server/models/user' file

Hi there! I'm currently working on an application with a folder structure as shown below. I want to use the following line in my passport.js file: var User = require('../server/models/user'); However, I encountered the error below after tr ...