What is the best way to handle arithmetic operations with multiple input fields in Angular?

In my form, users input number values which I need to send to my ts file for multiplication when a button is clicked. View screenshot example

Below are the code snippets:

  calculate(value0,value1){
    this.bindData(value0,value1);
  }

bindData(a,b){
    
    this.state=true;
    this.cshDvdnd=a*b;
    this.complete.emit(this.cshDvdnd);
  }
<label for="basic-url" class="form-label">Number of Shares:</label>
<div class="input-group">
    <span class="input-group-addon" id="numShares"></span>
    <input type="number" id="value0" name="value0" #value0 class="form-control" placeholder="Enter Total Number of Shares Owned ..." aria-describedby="numShares">
  </div>
  <br>
  <div *ngIf="buttonNumber==0">  
    <label for="basic-url" class="form-label">Cash Dividend:</label>
    <div class="input-group">
    <input type="number" id="value1" name="value1" #value1 class="form-control" placeholder="Net Amount per Share to be Distributed to Shareholders (₺) ..." aria-describedby="basic-addon2">
    <span class="input-group-addon" id="basic-addon2"></span>
  </div>
</div>
<button class="btn btn-primary" (click)="calculate(value0,value1)">Calculate</button>

How can I correctly multiply the input values of value1 and value2 from the HTML form? My bindData function is not functioning as expected.

Here is the webpage I am working on:

Answer №1

When using Angular, make use of ngModel to easily bind data OneWay or TwoWay.

For example:

<input
    type="number"
    [(ngModel)]="value0"
    class="form-control"
    placeholder="Enter Total Shares Owned..."
    aria-describedby="shareCount"
/>

No need to pass the value from HTML since it is already available in TS. This simplifies the calculation method.

HTML:

<button class="btn btn-primary" (click)="calculate()">Calculate</button>

TS:

value0: number;
value1: number;

calculate(){
   this.bindData(this.value0,this.value1);
}

bindData(a,b){
   this.result = a * b;
}

Your multiplication result is stored in the result variable, making it accessible anywhere.

Here is the Demo.

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

Tips for incorporating classes as a prop in material ui components

When working with material ui, I often find myself creating generic components where the styling is actually defined in a parent or grandparent component. For example: const GenericDescendant = (props: DescendantProps) => { const { classesFromAncestor ...

TS1055 occurs when utilizing async/await with a custom type alias

I defined a custom type alias: export type ActivationPromise = Promise<void>; I have created the following two functions: async function derp(): ActivationPromise { await test(); } function test(): ActivationPromise { return Promise.resol ...

Develop a "Read More" button using Angular and JavaScript

I am in search of all tags with the class containtText. I want to retrieve those tags which have a value consisting of more than 300 characters and then use continue for the value. However, when I implement this code: <div class=" col-md-12 col-xl-12 c ...

Struggling to Decode Octet-stream Data in Angular 6 HttpClient: Encountering Parsing Failure with Error Prompt: "Failed to parse HTTP response for..."

Is there a way to make a non-JSON request to the server using Angular 6 HttpClient (@angular/common/http) in order to receive an Octet-stream? Below is the code I have tried: getFile(file: any) { let headers = new HttpHeaders({ 'Content-T ...

Is it possible to expand the Angular Material Data Table Header Row to align with the width of the row content?

Issue with Angular Material Data Table Layout Link to relevant feature request on GitHub On this StackBlitz demo, the issue of rows bleeding through the header when scrolling to the right and the row lines not expanding past viewport width is evident. Ho ...

The C# private property is inaccessible during a TypeScript callback as it is not contained within the

I'm encountering an issue with TypeScript where the callback function is only returning _proto in the response's .data property when I set private properties in C# and instantiate an object filled with constructed properties. Strangely, if the pr ...

What is causing the error "has no properties in common with" in this wrapped styled-component?

When looking at the following code, Typescript is flagging an error on <HeaderInner>: [ts] Type '{ children: Element; }' has no properties in common with type 'IntrinsicAttributes & Pick & Partial>, "className"> & ...

Link a template to a formly field when clicking on another field within an Angular formly form

Recently, I have been utilizing a Formly form that includes a section for displaying dynamic HTML content. Within this form, I am using the template field to initialize some HTML content when the page loads. However, I have encountered an issue where chang ...

The SupabaseAuthClient type does not have a property named 'session' available

Here is the complete code snippet for page.tsx: "use client"; import React, { useState, useEffect } from "react"; import axios from "axios"; import { Session } from "@supabase/supabase-js"; import { Auth } from " ...

Utilizing TypeScript's Exclude feature with a generic type

An update to dependencies in my TypeScript-based Nodejs project has led to compilation errors when working with a generic class that manages mongoose models. The root cause appears to be related to how TypeScript handles generic types. To illustrate the i ...

Tips for importing "~bootstrap/scss/bootstrap" in a .html or .ts file while utilizing a carousel

I am looking to include the bootstrap carousel file in just one component, either a .ts or .html file. I do not want to have bootstrap integrated into the entire project via angular.json. Is it possible to import it into only one specific component? Does ...

Deactivate dates in angular material date range picker after a certain number of days

Utilizing the latest version 16 of Angular material date range picker with active action buttons as shown in this image https://i.stack.imgur.com/srZGn.png My current goal is to disable a specific number of days following the selected start date. For inst ...

Encountering an issue while trying to load a file from an API due to difficulties in parsing it to

When trying to load an xlsx file from an API, I encountered an error because Angular automatically tries to parse the body as JSON. To resolve this issue, I found that specifying the response type directly in the request works: this.http.get(this.url + " ...

Error in TypeScript when using Vue/Nuxt.js: The property 'latitude' is not found in the type '(() => any) | ComputedOptions<any>'

As a newcomer to Vue.js, I am currently utilizing it with Typescript on a Nuxt.js (v2.15.8) application. The code snippet provided below is functioning correctly: export default Vue.extend({ name: 'MyComponent', ...

In order to effectively manage the output of these loaders, it may be necessary to incorporate an extra loader. This can be achieved by using the

I'm currently working with react typescript and trying to implement a time zone picker using a select component. I attempted to utilize the npm package react-timezone-select, but encountered some console errors: index.js:1 ./node_modules/react-timezo ...

The authService is facing dependency resolution issues with the jwtService, causing a roadblock in the application's functionality

I'm puzzled by the error message I received: [Nest] 1276 - 25/04/2024 19:39:31 ERROR [ExceptionHandler] Nest can't resolve dependencies of the AuthService (?, JwtService). Please make sure that the argument UsersService at index [0] is availab ...

Ways to adjust height dynamically to auto in React

I am currently stuck on a problem concerning the adjustment of my listing's height dynamically from 300 to auto. My goal is to create a post-like feature where users can click "read more" to expand and view the full post without collapsing it complete ...

Setting up ESLint for TypeScript with JSX configuration

I am encountering problems with TypeScript configuration. Below is the code snippet from my tsconfig.json: { "compilerOptions": { "target": "es5", "lib": [ "dom", "dom.iterable", "esnext" ], "allowJs": true, "skipLib ...

Browser inspect tool is failing to hit breakpoints when using USB-connected device

While troubleshooting my Ionic Capacitor application on a USB connected device, I noticed that my browser dev-tools (Chrome, Edge, Firefox) are not hitting my breakpoints in the source code. Interestingly, when I run the application on ionic serve, everyt ...

The program encountered an issue with determining the length of this.slides. The property 'length' is undefined and cannot be

console.log(this.slides.length()); displays Cannot read property 'length' of undefined. After a setTimeout of 100 milliseconds, this message will appear. Is there a way to determine if a child component has finished loading from the parent compo ...