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

Looking for a regular expression to verify if the URL inputted is valid in TypeScript

After conducting thorough research, I discovered that none of the suggested URLs met my criteria, prompting me to raise a new query. Here are my specific requirements: * The URL may or may not include 'http' or 'https' * The URL can co ...

Issue: Keeping the mat-form-field element in a single line

I am facing an issue with incorporating multiple filters for each column in an angular material table. I cannot figure out why the filter input is not moving to a new line under the header. Here is an image for reference -> Angular material table with m ...

New Chrome update restricts insecure cookies from functioning in Angular

We have been utilizing the ngx-cookie-service to establish session cookies for our logged-in users. Everything was functioning properly until yesterday when the latest Chrome update began blocking unsecure cookies and displaying a warning message in the co ...

Sending a POST request to an API with Angular and passing an object as the payload

I'm currently working on adding a feature to my app where I can take the products from an order and send them to the cart, essentially replicating the entire order. While I have successfully retrieved the order, I am facing difficulty in sending it b ...

Setting the initial navigation theme based on route parameters from an external source, not within the StackNavigator

Is there a way to set the initial navigation theme based on the current route params without rendering the NavigationContainer and causing a flash of content with the default theme? Can the route be accessed from outside of the NavigationContainer without ...

Refreshing Angular 9 component elements when data is updated

Currently, I am working with Angular 9 and facing an issue where the data of a menu item does not dynamically change when a user logs in. The problem arises because the menu loads along with the home page initially, causing the changes in data to not be re ...

Tips for accessing images in Angular 24 lazy loaded modules

I have a collection of images that need to be shared throughout my application. There are 2 lazy-loaded modules - Login and Overview. The image I require is located in src/assets/images/logo.png and needs to be accessible in both the Login and Overview com ...

Install NPM without changing directories to the folder

Currently, I am using Windows Powershell and a pipeline to create the package for an application deployment. Here is the pipeline setup: https://i.stack.imgur.com/am2iR.png My current obstacle revolves around the "npm install" command, as I want to avoid ...

Building with Angular seems to be dragging on forever

Working with Angular 6.7 on a finance application that consists of over 80 modules. When I run the build using the command: node --max_old_space_size=16384 ./node_modules/@angular/cli/bin/ng build --prod The build process takes more than 90 minutes to com ...

Can you explain the significance of the additional pipeline in the type declaration in TypeScript?

Just recently, I defined a type as follows- interface SomeType { property: { a: number; b: string; } | undefined; } However, upon saving the type, vscode (or maybe prettier) changes it to- interface SomeType { property: | { a: nu ...

The benefits of a modular design in a React and TypeScript library

Following a tutorial on creating a library with React, Typescript, and rollup, I successfully managed to get everything working. However, as my project grows with additional features, I'm looking to have modular exports similar to what is seen in redu ...

Triggering a subsequent action in Ngrx depending on the data from the initial action

Currently, I am fetching a list of users using ngrx: this.users$ = this.store.select(fromReducer.getUsers); In my HTML template: <ul> <li *ngFor="let user of users$ | async"> {{user.id}} - {{user.name}} - {{user.email}} </ ...

What steps are involved in developing an Angular library wrapper for a pre-existing Javascript library?

Imagine having a vanilla Javascript library that is commonly used on websites without any frameworks. How can you create an Angular library that can be easily installed via npm to seamlessly integrate the library into an Angular application? The process o ...

Attempting to retrieve a URL using Angular/Typescript is generating an Unknown Error instead of the expected successful response

I'm trying to make a simple HTTP function call through TypeScript (Angular) to an API hosted as a function in Azure. When I call the URL through Postman or directly in the browser, everything works perfectly. However, when I try to call the URL usin ...

Page refreshing in Angular 5 consistently redirects to the home page instead of staying on the current page

I am experiencing an issue with the navigation on my application. When I navigate to routes like getEmp-by-id or page-not-found and hit refresh, the application automatically redirects me back to app-home. However, I would like it to stay on the same pag ...

Differences between Angular TS Lint onInit and ngOnInit

My TS Lint issue warned me to implement the OnInit interface and included a link to this page: https://angular.io/docs/ts/latest/guide/style-guide.html#!#09-01 I'm curious, what sets apart `onInit` from `ngOnInit`? Both seem to work just fine for me. ...

Retrieve the service variable in the routing file

How do I access the service variable in my routing file? I created a UserService with a variable named user and I need to use that variable in my routing file. Here is the approach I tried, but it didn't work: In the routing file, I attempted: cons ...

An issue has occurred while utilizing Angular

I'm diving into the world of Angular and encountering some errors as I try to execute this code. An unexpected token is causing trouble. A constructor, method, accessor, or property was expected. The left side of a comma operator seems to be unused ...

The error message "TypeError: self.parent.parent.context.parseInt is not a function" indicates that

My goal is to set the height of an image using ngStyle by calculating it with a Math operation in the following way: <div [ngSwitch]="tbNm?tbNm:'itm0'"> <ion-list *ngFor="let vl of scrnshot;let ind=index"> <img *ngSwitch ...

Using Vue 2 with a personalized Axios setup, integrating Vuex, and incorporating Typescript for a robust

I'm still getting the hang of Typescript, but I'm facing some challenges with it when using Vuex/Axios. Current setup includes: Vue CLI app, Vue 2, Vuex 3, Axios, Typescript At a high level, I have a custom Axios instance where I configure the ...