Calculating Events with the onChange Method in Typescript

How do I calculate the total ticket price when I adjust the number of individuals?

HTML Code :

<div class="row">
    <div class="col-md-6">
        <label for="person">Person</label>
        <div class="form-group">
            <input type="number" class="form-control" formControlName="person" id="input" (change)="countPrice($event)">

        </div>
    </div>

<div class="row">
    <div class="col-md-6">
        <label for="price">Price</label>
        <div class="form-group">
            <input type="number" class="form-control" id="output" formControlName="price" (change)="countPrice($event)">>
        </div>
    </div>
</div>

Typescript Code:

onDestination(eve) {
  this.http.post(environment.api_url + `/admin/get_price`, {

    "from_city": this.r.from_city.value,
    "to_city": this.r.to_city.value,

  }).subscribe(data => {
    console.log(data);
    this.price = data['data']['price'];
    console.log(this.price);
    this.bookingForm.patchValue({
      'price': this.price
    });
  })
}
countPrice(event) {

}

I am looking to display the total price by calculating it based on the number of people. I need assistance in retrieving the price from the previous change event. Any help would be greatly appreciated.

Answer №1

If you're looking for a solution, consider using valueChanges.

this.formData.get('user').valueChanges.subscribe(val => this.updateCounter(val));

After that, the method updateCounter() can handle the calculation and return the result:

updateCounter(totalUsers: number): number {
    return this.price * totalUsers;
}

https://angular.io/guide/reactive-forms#managing-control-values

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

Embedding Globalize.js into an Angular component

Hey there! I'm currently working on building an Angular 4 application that needs to support L10n. I've decided to incorporate globalize into my project. Below is a snippet of my App component: import { Component, OnInit } from '@angular/c ...

Tips for incorporating ngIf within a td element

My dilemma is with a table I have that displays data from a database. I need to be able to edit the data based on certain qualifications, so I want to include two buttons - one for deleting and one for editing. These buttons should only be enabled if the r ...

Utilize Angular to transform a JSON string into HTML text featuring organized bullet points

I am currently working on a project using Angular and I need to display some data from a JSON file on a webpage. The issue I am facing is that the message is quite lengthy, and I would like it to be presented in bulleted points. "messageToDisplay" ...

A guide to adding a delay in the RxJS retry function

I am currently implementing the retry function with a delay in my code. My expectation is that the function will be called after a 1000ms delay, but for some reason it's not happening. Can anyone help me identify the error here? When I check the conso ...

leveraging external libraries with angular

Is there a way to integrate third-party libraries into Angular 4? Typically, I follow the code snippet below: <html> <head> <title>Bootstrap CDN Simple Example</title> <link href="//netdna.bootstrapcdn.com/ ...

Issue with importing aliases in Angular 7 production environment

Hello everyone! I have encountered an issue where using alias on import and building the project in production mode (--prod flag) results in the alias being undefined. Interestingly, this behavior does not occur in development mode. Any suggestions on how ...

Guide on transitioning Angular 2 RC 1 (or an earlier version) Forms to the new Forms in Angular 2 RC 2 / RC 4

I am currently in the process of upgrading my Angular 2 RC 1 app to Angular 2 RC 4, and part of this update involves migrating my existing forms to Angular 2 RC 4 New Forms. Could someone provide guidance on how to successfully update my existing forms to ...

Automatically select a value in MUI AutoComplete and retrieve the corresponding object

I recently set up a list using the MUI (v4) Select component. I've received a feature request to make this list searchable due to its extensive length. Unfortunately, it appears that the only option within MUI library for this functionality is the Au ...

Setting limits to disable or remove specific times from the time picker input box in Angular

I'm having trouble with a time input box. <input type="time" min="09:00" max="18:00" \> Even though I have set the min and max attributes to values of 09:00 and 18:00 respectively, it doesn't seem to be working properly. I want to ...

What is the best way to securely store a JWT Token received from Cognito after logging in through the Cognito Hosted UI?

Our current architecture involves front end Angular and backend nodejs/express. This setup functions in the following order: User logs in to the site via Cognito Hosted UI Upon successful login, the user is redirected to our home page with a code sent in ...

The error message "Angular 8: Type 'void' cannot be assigned to type 'ObservableInput<any>'" indicates a type mismatch in the Angular 8 code

I am having an issue with a method that needs to be called every 5 minutes to check a user's network connectivity. I keep getting the following error message and I can't figure out what it means: Type 'void' is not assignable to type &a ...

Tips for utilizing regex to locate words and spaces within a text?

I'm feeling so frustrated and lost right now. Any help you can offer would be greatly appreciated. I am currently dealing with an issue in Katex and Guppy keyboard. My goal is to create a regex that will identify the word matrix, locate the slash that ...

I am puzzled as to why I keep receiving the error message "Cannot read property 'poPanel' of undefined"

CSS In my project, I am implementing a feature that displays an ordered list by looping through an array of objects and adding them on a button click. It works smoothly for adding items, but when I try to implement a remove function to delete each item, I ...

There was a Runtime Error that occurred, stating a TypeError: It is not possible to access properties of an undefined value (specifically

I've encountered an issue with a donut chart implemented from react-apex charts. Every time I try to render the page containing the chart, an error occurs. However, if I make changes to a property of the chart, it renders without any errors on the fro ...

If an interface property is set as (), what significance does it hold?

While exploring the Vue.js source code located at packages/reactivity/src/effects.ts, I came across this snippet: export interface ReactiveEffectRunner<T = any> { (): T effect: ReactiveEffect } I'm curious, what does () signify in the code ...

We encountered an unhandled error: It is impossible to assign a value to the property '_showWarnings' of the object '#<Object>'

Looking to implement SSR on my current website. Angular version: v8 Followed the instructions from this link: https://angular.io/guide/universal [error] TypeError: Cannot assign to read only property '_showWarnings' of object '#<Object& ...

Is Typescript familiar with the import -> require syntax, but unfamiliar with the require -> import syntax?

My code includes a simple file that utilizes the ES6 module loader: 1.ts import {foo} from "./2" foo('hello'); 2.ts function foo (a){console.log(a);}; export {foo} When the tsconfig is configured as follows: "module": "commonjs", We can o ...

I am experiencing difficulties with *ngIf in my HTML as it is not functioning properly, however, the ng

I have come across many inquiries related to this issue, but none of them proved helpful for me. Below is my HTML code: <div class="pl-lg-4"> <div *ngIf="isStorySelected; else hi" class="row"> ...

The npm lint command is throwing an "Observable `source is deprecated`" error

When I execute the command npm lint on my code, I receive a warning stating "source is deprecated: This is an internal implementation detail, do not use." The specific part of the code causing this issue is shown below: set stream(source: Observable<a ...

Experiencing a Typescript error when trying to access a property within a nested object

My current challenge involves typing an object, which seems to be error-free until I try to access a nested property and encounter the dreaded red squiggle. After some research, I came across suggestions like this: type FlagValue = string | boolean | numb ...