I'm puzzled as to why my createDoorMethod is returning a string value instead of a number, even though I am passing it a number. Can someone help me

Currently enrolled in a web development course, I am diving into the world of Angular 2 and TypeScript. Despite following along with the video tutorial and using the same code, my implementation is not working as expected, leaving me puzzled.

Here is the component snippet:

  createDoor(width:number, height: number, type: string) {
    const payload = {width_in: width, height_in: height, type}
    this.http.post<Door>(`${this.baseURL}/door`, payload).subscribe(
      response => {
        this.doors.push(response)
      }
    )
  }

And here is the HTML component:


<h1> See all doors </h1>

<ul *ngIf="doors.length > 0">
    <li *ngFor="let door of doors">
        <p> {{ door.type }} door ({{door.width_in}} x {{door.height_in}})</p>
    </li>
</ul>

<p *ngIf="doors.length === 0"> No new doors yet. Create one below</p>

<h1>Create a new door below</h1>

<label for="width">Width:</label>
<input name="width" type="number" id="width"  placeholder="Add a door width" required #width>

<label for="height">height:</label>
<input name="height" type="number" id='height' placeholder="Add a door height" required #height>

<label for="type">Type</label>
<select name="type" id="type" id="type" #type>
    <option value="" selected>Please choose</option>

    <option value="Sliding">Sliding</option>
    <option value="Basic">Basic</option>
    <option value="Automatic">Automatic</option>
</select>

<button (click)='createDoor(width.value, height.value, type.value)'>Create door</button>

The issue seems to be related to this line:

<button (click)='createDoor(width.value, height.value, type.value)'>Create door</button>

I'm struggling to understand why the click function is not receiving the correct parameters. It's expecting a string instead of a number even though I provide a numeric value. Any insights or suggestions would be greatly appreciated.

Answer №1

The use of type="number" only restricts the type in the browser, resulting in a string value when accessed in TypeScript. To obtain a number, manual conversion is required (e.g., using the + sign).

To learn more on this topic, refer to: html-input-type-number

Answer №2

Simply take it in as a string and then convert it using parseInt. It's just a small communication gap between the DOM and JavaScript/TypeScript.

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

Encountering a console error: Prop type validation failed for the `Rating` component with the message that the prop `value` is required but is currently `undefined`

I am encountering a proptype error which is causing an issue with the URL display on my Chrome browser. Instead of showing a proper address, I am seeing the URL as undefined like this: http://localhost:3000/order/undefined Instead of undefined, I should h ...

Implement a logging system to track and record data from both incoming requests and outgoing responses on a server powered by Express and Node.js

Is there a way for my server to log the response and request data when posting to another server? Thank you. const request = require('request'); postToIotPlatform = function postToIotPlatform(req, res, next) { var formData = JSON.stringify( ...

Crockford's system for safeguarded entities

Despite the abundance of questions and resources related to "Javascript: The Good Parts," I am struggling to comprehend a specific sentence in the book. On pages 41-42, the author defines the serial_maker function as follows: var serial_maker = function ( ...

When JSON contains slashes, JSON.parse will trigger an error

I am struggling with a valid JSON generated using PHP like this: var json = <?php echo json_encode(['somearray']); ?>. Inside the array, there is an HTML string as shown below: $myArray = ['image' => '<img src="/img/f ...

Is it possible to modify the sizes parameter of the GPUComputationRenderer?

Currently, I am utilizing gpuCompute = new GPUComputationRenderer( sizeX, sizeY, renderer ); for texture purposes. I am looking to update the values of sizeX and sizeY within this code snippet. However, after searching through the library, I have not been ...

How can Angular HttpClient be used to convert from Http: JSON.parse(JSON.stringify(data))._body?

When using the Http module, you can use this method: Http service: let apiUrl = this.apiUrl + 'login'; let headers = new Headers({'Content-Type': 'application/json'}); return this.http.post(apiUrl, JSON.stringify(model), {h ...

Is it possible to send two parameters to a JavaScript function using HTML?

Seeking help to develop an .html page where two string inputs are passed as parameters to a .js function, which then returns the longer of the two strings based on their lengths. Initially, I successfully created a functional .js script in VS CODE. Here i ...

Perform an AJAX request to an encrypted URL with an unverified certificate

I'm experiencing an issue with my site that makes AJAX JSONP calls to a secured (SSL) web server. Everything works smoothly when using an unsecured (HTTP) web server, but once I switch to the SSL version, the call never returns. After checking with Fi ...

Guide on adding an item to the end of an array with an arrow function

const appendElement = (item) => { return (list) => { }; }; Add a new item to the end of the list. Parameters item (any): The item to add. Output (Array) => Array: Generates a closure that duplicates the original list with the added ite ...

React JS Button remains unaltered despite API call influence

I have encountered an issue with my page where a single post is displayed and there is a like button. The problem arises when the user clicks the like button - if the post is already liked, the button state should change to an unlike button. However, if th ...

Delayed response of text effects in JQuery on page load

Within my rails app, I have the following code snippet: window.onload = -> $("#mycontainer").typewriter() $("#div1").fadeIn("slow") This code snippet interacts with the following block of content: <blockquote class="pull-left"> < ...

The value of a Vue.js directive expression is consistently found to be undefined

I created a compact jsfiddle to show how to access directive values within the bind function. However, it seems to always return undefined. Check out the demo here! bind: function(){ console.log(this.value); this.el.innerText = this.value; } ...

What is the best way to incorporate a subcategory within a string and separate them by commas using Vue.js?

Is it possible to post subcategories in the following format now? Here is the current result: subcategory[] : Healthcare subcategory[] : education However, I would like to have them as a string separated by commas. This is my HTML code: <div id="sub ...

What mechanism enables the scores on this sports ticker to refresh automatically without relying on ajax calls?

While browsing scores on , I found myself intrigued by the way they update their scores without using ajax calls or iframes. It's a mystery to me how this functionality is achieved. Can anyone shed some light on how it works? ...

The Mongoose connection keeps failing to reconnect and maintain a stable heartbeat

I am facing an issue with the automatic reconnection feature in mongoose on my project. Despite configuring it to reconnect after a certain interval, it does not work as expected. Even if the credentials are correct, mongoose should attempt to log in perio ...

What sets apart the ? operator from incorporating undefined in the type declaration?

Can you explain the distinctions among these options? type A = {a?: string} type A = {a: string | undefined} type A = {a?: string | undefined} In what scenarios would one be preferred over the others? For more information, visit: https://github.com/mic ...

What causes the variance in outcomes between employing a literal string versus a local variable?

Here is a loop that I am working with: for (var key in criteria) { var exists = Object.keys(item).some(function(k) { return item[k] === "Test"; }) } Initially, this loop functions as expected and returns 15 trues based on the number of i ...

Navigating global variables and functions in Vue3 with TypeScript

Feeling lost in the world of Vue.js, seeking guidance here. Attempting to handle global data and its corresponding functions has led me on a journey. Initially, I experimented with declaring a global variable. But as more functions came into play, I trans ...

Multi-object retrieval feature in Material Dialog

I am encountering an issue with Material Dialog when confirming the action to "remove row" in a table. Initially, removing from the dialog works fine and deletes a row. However, after closing the dialog and re-calling it for the second time, the removal ac ...

View complex response objects in Postman as easily digestible tables

I am interested in displaying the data provided below as a table using Postman Tests. The table should have columns for product, price, and quantity, with Items listed in rows. It's important to note that there may be multiple shippingGroups within th ...