What is the best way to display computed values from variables in Angular?

In one of my components, I have a FormGroup set up like this:

form: FormGroup = new FormGroup({
    $key: new FormControl(null),
    from: new FormControl('', Validators.required),
    to: new FormControl('', Validators.required),
    quantity: new FormControl('', [Validators.required, Validators.pattern('[0-9]*')]),
    price: new FormControl('', [Validators.required, Validators.pattern('[0-9]*')]),
    ticker: new FormControl('', Validators.required)
  });

Within the HTML file, I have input elements for each of the five form controls to accept user inputs.

However, I'm running into an issue when trying to display the calculated Amount in the HTML:

<p>Amount: {{ form.controls['quantity'] * form.controls['price']}}</p>

The errors I'm encountering are:

The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.

The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.

Could someone provide some guidance on what might be causing this issue?

Answer №1

Transform the variables into numerical values.

Give this a shot:

<p>Total Amount: {{ +form.controls['quantity'] * +form.controls['price']}}</p>

Alternatively, update your input fields to type number:

<input type="number" formControlName="quantity">
<input type="number" formControlName="price">

Don't forget to adjust your form like this:

quantity: new FormControl(null, Validators.required),
price: new FormControl(null, Validators.required),

Answer №2

Shout out to @Bazhan for the help, but it turns out that the following tweak produced the desired result:

<p>Total: {{ form.value.quantity * form.value['price']}}</p>

Instead of referencing the controls field, I needed to access the value field.

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

Vue: Defining typed props interface including optional properties

I created a method that I want to be accessible on all my Vue instances, so I can use it in case of an error and display a specific error component. Similar to the functionality provided by vue-error-page. Since I am working with typescript, I now want to ...

What is the best way to restrict a React input field to have values within the minimum and maximum limits set by its

As a newcomer to React, I am working on restricting my input to values between -10 and 10. Currently, the input is set up to accept any value, and I am utilizing hooks like useState and useEffect to dynamically change and set the input value. My goal is ...

Using Typescript to define the type for React's useState() setter function whenever

I'm working on setting up a React Context to handle parameters mode and setMode, which act as getter and setter for a React state. This is necessary in order to update the CSS mode (light / dark) from child components. I'm encountering a Typescr ...

Tips on accessing the JS file api within an angular component.ts file

I've got a function in my JS file located at src/server/js/controller.js, and I'm trying to use that API within a component's ts file. I attempted the following code to achieve this but it doesn't seem to be working properly. controlle ...

A proposal for implementing constructor parameter properties in ECMAScript

TypeScript provides a convenient syntax for constructor parameter properties, allowing you to write code like this: constructor(a, public b, private _c) {} This is essentially shorthand for the following code: constructor(a, b, _c) { this.b = b; thi ...

Iterate through the Ionic3/Angular4 object using a loop

I've been attempting to cycle through some content. While I tried a few solutions from StackOverflow, none seem to be effective in my case. Here is the JSON data I am working with: { "-KmdNgomUUnfV8fkzne_":{ "name":"Abastecimento" }, ...

Winston logs are unable to function within the Docker Container

I'm currently working on developing a nodejs/express app with typescript and have recently installed the winston package using npm install winston. I came across this helpful article that I've been following closely. Now, my goal is to dockerize ...

Unable to assign values using Promises in an Angular component

While working on a Component HTML file, I encountered an issue with exposing a variable. The variable was supposed to retrieve a value from the response using cl.getMonitors. Strangely, despite seeing console.dir(res) in the console, the value of the var ...

Switch over to TypeScript - combining Socket.IO, Angular, and Node.js

This is the code I'm using for my node server: import http from 'http'; import Debug from 'debug'; import socketio, { Server } from 'socket.io'; import app from './app'; import ServerGlobal from './serve ...

How can Visual Studio assist in developing npm scoped modules?

I am new to nodejs/typescript/visual studio development and could use some guidance. I'm embarking on a new vs2015 solution to create multiple nodejs scoped modules. I have a few questions: What is the best way to organize my project folders? Is th ...

There was an issue converting the value {null} to the data type 'System.Int32', resulting in a 400 error

Attempting to make a POST request with some missing data is causing errors in my angular form. Here is the payload I am using: DeviceDetail{ deviceId:'332', sideId: null, deviceName:'test' } Unfortunately, I encountered a 400 bad re ...

The CORS policy has blocked access to XMLHttpRequest at 'https://saja.smjd.ir/api/Account/login' from the specified origin 'http://**'

I have successfully completed my project using Angular 9 on the frontend and asp.net core 3 on the backend, and deployed it to a server. However, I am facing an issue when trying to obtain or use a token from the server. Access to XMLHttpRequest at 'h ...

State mutation not reflected in input field value update

During the development of a small project for educational purposes, I encountered an issue with updating the input value. Below is the simplified component causing this issue. function TipSelector({selections, onTipChanged}: {selections: TipSelectorItem[], ...

Issue in Angular 4 unit test: Unable to access 'injector' property due to its null value

I have the following test (using karma and jasmine). Please note that I call initTestEnvironment elsewhere, but I have verified that it gets called (with a console.log). Every time I run it, I encounter: TypeError: Cannot read property 'injector&apos ...

The View is not reflecting changes in the Variable

Is there a way to disable all the buttons when selectedplace is null in the Dialog, as it currently works when the Dialog first starts but remains activated all the time when the option is changed? I have attempted the following: Customized HTML: ...

Adapt button functionality according to selected dropdown value in Angular

I have implemented a License Key generation process in my application where user input is used to create a unique key that is then passed to the Java backend. The code snippet for generating the key is as follows: @PostMapping("/generate") public Li ...

collection of assurances and the Promise.all() method

Currently, I am dealing with an array of Promises that looks like this: let promisesArray = [ service1.load('blabla'), service2.load(), // throws an error ]; My goal is to execute all these Promises and handle any errors that occur, as ...

Is it possible to specify the version of a dependency using Stackblitz?

Is it possible to specify the dependency version on StackBlitz? I recently updated the dependency on NPM, however StackBlitz seems to be stuck on installing the old version. ...

The user type is not yet loaded from Firestore when the view is rendered

I am currently in the process of developing an Ionic - Angular application that allows hospital patients to submit requests to nursing staff, who can then view the assigned requests based on the patient's room. Nurses have access to all requests, whil ...

Navigating to a pre-defined default route in Angular 2 with content

Is there a way to set a default route using the updated RC router? @Routes([{ path: '/', component: Home }]) What if I want to display a page with a non-empty path initially? For example: @Routes([{ path: '/home', component: Home } ...