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

Searching for data across multiple tables using the Laravel framework combined with Vue.js and API integration

I am currently implementing a multi-search feature for a single table The search functionality is functioning correctly but only for one column Here is the snippet from my controller: public function index() { return Matter::when(request('sear ...

Encountering an Angular error while trying to use the command "npm run dev:ssr" to observe server-side rendering on the localhost

When I run this command, it starts listening on port 4200 but the page keeps loading without ever fully loading and shows this error in the command prompt: Unhandled Promise rejection: connect ECONNREFUSED 127.0.0.1:6379 ; Zone: <root> ; Task: Promis ...

Issue encountered while attempting to log out a user using Keycloak in a React JS application

I'm currently working on implementing authentication for a React JS app using Keycloak. To manage the global states, specifically keycloackValue and authenticated in KeycloackContext, I have opted to use React Context. Specific Cases: Upon initial r ...

Exploring the Integration of JSONAPI Included with Angular Observables

Currently, I am in the process of learning how to extract Drupal 8 content into my Angular 7 application using jsonapi. This journey started after reading Preston So's enlightening book on Decoupled Drupal in Practice. However, the guide fell short of ...

The server is taking too long to respond, resulting in a 504 Timeout error

I currently have an Angular frontend paired with a .NET CORE backend. The issue I am experiencing is related to a specific request that is resource-intensive and takes a significant amount of time to complete. Whenever I check the browser console, I receiv ...

Tips for preventing the need to convert dates to strings when receiving an object from a web API

I am facing an issue with a class: export class TestClass { paymentDate: Date; } Whenever I retrieve an object of this class from a server API, the paymentDate field comes as a string instead of a Date object. This prevents me from calling the ...

Submit the form without displaying any output in the browser, not even in the view source code

I have a basic form that needs to be submitted multiple times, but I want the submission process to be hidden from the browser. Simply using "hidden" or "display:none" won't completely hide the form code when viewing the page source. I tried using PHP ...

Invoke a PHP function located in a separate file using a JavaScript function to fetch data from a database

How can I properly call a PHP function from a JavaScript function located in a different file? I am trying to pass a variable from an onClick function in JavaScript to a PHP function, which will then access a MySQL database to retrieve data. However, my c ...

Transform the column's datetime into a date in the where condition when using sequelize

Hey there, I'm looking to convert a datetime column into just date format while running a query. Could someone assist me with creating a Sequelize query based on the example below? select * from ev_events where DATE(event_date) <= '2016-10- ...

Implementing handleRequest as an asynchronous function within the passportjs guard

@Injectable() export class RefreshAuthGuard extends JwtAuthGuard { constructor( private readonly jwtService: JwtService, ) { super(); } public handleRequest(err: any, user: any, info: Error, ctx: any): any { if (err ...

Generating a client-side MD5 hash for an image file in order to compare it to the hash calculated by Firebase?

Is there a way to calculate the MD5 of an image file on the client side within my Angular Map application, that will match the MD5 when I store the file on Firestore? I need to verify that a user's file matches a reference version stored in Firebase ...

Using a package with `webfontloader` in NextJs for Server-Side Rendering: A guide

Currently, I am working on creating an application with nextJS and incorporating a package that utilizes Webfontloader internally. After installing the library, my application encountered an error preventing it from running successfully. It seems like th ...

Having trouble transmitting data from the View to the Controller

Need help with this issue. I'm having trouble passing my data to the controller. Below is my ajax code. <script type="text/javascript"> $(document).on("click", "#login_button", function () { var userName = document.getElementById(" ...

Programmatically selecting a row in Angular Datatables

I have an Angular 8 application with the Angular Datatables plugin installed. My goal is to programmatically select a row based on the id parameter from the URL http://localhost:5000/users;id=1. this.route.paramMap.subscribe((params: ParamMap) => { ...

trim() function acting strangely

There seems to be an unexpected occurrence with the trim() function, as it is removing the á character. https://i.stack.imgur.com/whZBN.png This particular code snippet is typically used in various JavaScript projects without any issues. However, a clie ...

Saving data from Material UI forms in TypeScript

Is there an effective method for storing values entered into the text fields on this page? const AddUserPage = () => ( <div> <PermanentDrawerLeft></PermanentDrawerLeft> <div className='main-content'> < ...

Utilizing next-redux-wrapper within the getServerSideProps function in Next.js allows for seamless

When trying to call an action function in getServerSideProps using TypeScript, I encountered some challenges. In JavaScript, it is straightforward: import { wrapper } from "Redux/store"; import { getVideo } from "Redux/Actions/videoAction&qu ...

Utilizing TypeScript with Express.js req.params: A Comprehensive Guide

Having an issue with my express.js controller where I am unable to use req.params The error message being displayed is 'Property 'id' is missing in type 'ParamsDictionary' but required in type 'IParam'.' I need a w ...

Are there alternative methods, aside from using a computed property, that can be utilized to store a Vue route parameter in a way where

In my Vue component, I am working on passing a route parameter through XHR requests and potentially using it in other areas as well. Initially, I considered storing it as a data attribute but realized that it could be modified by someone. Then it occurred ...

The issue with the antd Input component's onChange event not updating state correctly when using a list fetched from an axios get request in a React

Recently delving into React, I've dedicated the past week to honing my skills. My current project involves creating a straightforward application featuring a 'product create' form alongside a product list equipped with a search bar (utilizin ...