Generate dynamic property values based on calculations

I am facing a challenge with a form that I have designed. Could you guide me on how to dynamically update the value of the calculate field (contingency) whenever the user modifies the values of budget1 and budget2? I have attempted several approaches without success so far.

.html

    <form [formGroup]="form" (submit)="createOrUpdate(form)" novalidate>
        <ion-item>
          <ion-input type="text" formControlName="budget1" [(ngModel)]="project.budget1"></ion-input>
        </ion-item>
        <ion-item>
         <ion-input type="number" formControlName="budget2" [(ngModel)]="project.budget2"></ion-input>
        </ion-item>
       <ion-item>
       <ion-input type="text" formControlName="contingency" [(ngModel)]="project.contingency" disabled></ion-input>
       </ion-item>
   </form>

model.ts

export class ProjectDetail {
    budget1: number;
    budget2: number;
    contingency: number;
 }

.ts

export class ProjectComponent {

  @Input() data: any;
  @Output() onSelectProject: EventEmitter<any> = new EventEmitter<any>();
  form: FormGroup; project: ProjectDetail = new ProjectDetail();

  constructor(private formBuilder: FormBuilder) {
    this.initForm();
  }

  //initialize Form
  initForm() {
    this.form = this.formBuilder.group({
      budget1: ['', Validators.required],
      budget2: ['', Validators.required],
      contingency: [{ value: 0, disabled: true }],
    });
  }
}

Answer №1

If you want to perform calculations based on user input using ngModelChange, you can pass the values to a function and process them within that function.

 <ion-item>
          <ion-input type="text" (ngModelChange)="calculateContingency()" formControlName="budget1" [(ngModel)]="project.budget1"></ion-input>
        </ion-item>
        <ion-item>
         <ion-input type="number" (ngModelChange)="calculateContingency()" formControlName="budget2" [(ngModel)]="project.budget2"></ion-input>
        </ion-item>
 <ion-item>

In your TS file:

calculateContingency(){
   this.contingency = this.project.budget2 + this.project.budget1;
}

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

The issue with npm modules not appearing in EMCA2015 JS imports persists

I am currently in the process of developing a mobile application with Nativescript using the Microsoft Azure SDK. To get started, I installed the SDK via npm by running this command: $ npm install azure-mobile-apps-client --save However, upon attempting ...

The placeholder text in the matInput field is not being displayed

As a newcomer to Angular, I am facing a challenge that has left me unable to find a solution. Below is the code snippet in question: <mat-form-field> <input matInput placeholder="ZIP" style="color:red;"> </mat-form-field& ...

The Main Page is always the default destination when navigating with Angular Router

Having an issue with Angular Router (Angular 11). Here is my routing configuration: {path: '', redirectTo: '/login', pathMatch: 'full'} {path: 'login', component: LoginComponent} {path: 'verdicts', componen ...

Angular Error: The function is expecting a different type of input than what is being provided

Currently in the process of learning angular, I have a goal to create a service with a boolean observable and subscribe to it. I stumbled upon this tutorial that aligns closely with what I want - hiding menu nav links when a user is not logged in. In my ...

Restrict the discriminator value in a discriminated union from any other string literal union type in TypeScript

My discriminated union is quite basic, but I want to restrict the discriminator to only allow specific values that come from another string literal union type. This would simplify the process of adding new "cases" to the discriminated union. Here is a str ...

Tips and tricks for displaying JSON data in Angular 2.4.10

In my Angular project, I am facing an issue while trying to display specific JSON data instead of the entire JSON object. Scenario 1 : import { Component, OnInit } from '@angular/core'; import { HttpService } from 'app/http.service'; ...

What is the process for creating a new Object based on an interface in Typescript?

I am dealing with an interface that looks like this: interface Response { items: { productId: string; productName: string; price: number; }[] } interface APIResponse { items: { productId: string; produc ...

Restricting the selection of only one checkbox in an Ionic4 application

Currently working on enabling only one checkbox in my Ionic 4 app. I've made some progress with the code but now I'm stuck. I believe I need to implement ngModel for this task. The goal is to set response.checked to true when a checkbox is checke ...

Encountering a problem when trying to use event.target.value in an Angular TypeScript application

Here is the code from my app.component.html : <h1>Password Generator</h1> <div> <label>Length</label> </div> <input (input)="onChangeLength($event.target.value)"/> <div> <div> <input ...

It seems like there is an issue with your network connection. Please try again

Recently, I made the switch to EndeavourOS, which is based on Archlinux. I completed all my installations without any issues and attempted to create a new NestJs project after installing NVM, Node's latest version, and the NestJs/cli. However, when I ...

The object is given a value in the form of a string, even though it is a strongly-typed variable

I'm encountering something unusual in my code. In the following example, there is a (change) event that captures the current value selected by the user from a dropdown menu. <div style="padding-right: 0; width: 100%;"> <label st ...

Steps for integrating custom slot properties in MUI data grids

Custom pagination has been successfully implemented using the mui datagrid component. However, when attempting to pass props for pagination using datagrid's slotProps, an issue arises stating that the type of onChange does not match. How can this be c ...

Does the value of an Angular reactive form control only reflect what the user inputs?

I am working with a reactive form where I need to extract values and assign them to a variable defined in an interface. The form is populated using the Google Places API, which disables user interaction with all controls except for the initial address inpu ...

What is the significance of utilizing an empty value `[]` for a typed array interface instead of using an empty `{}` for a typed object interface?

Why can I initialize friends below as an empty array [], but not do the same for session with an empty object {}? Is there a way to use the empty object without needing to make all keys optional in the interface? const initialState: { friends: Array< ...

Acknowledgment Pop-up

When using the PrimeNG table with a custom modal component that I created, I encountered an issue. The edit functionality works correctly and retrieves the correct row id, however, the delete function always returns the id of the first row. dashboard.html ...

Generating a form structure from json containing repeated inputs: Control with path formArray could not be located

Currently, I am in the process of constructing a form using JSON data. My backend is implemented with Spring Boot, which returns the following object to an Angular frontend: { "controls": [ { "name": "genre", ...

Typescript encounters difficulty locating the Express module

My venture into creating my debut NodeJS application has hit a roadblock. Following advice from multiple blogs, I have been attempting to build my first nodejs app in typescript by following the steps below: npm install -g express-generator npm install - ...

The creation of a fresh child instance in Typescript using rest parameters

My goal is to create a parent class that allows children to generate new instances of the same child type. When I specify the number of parameters, everything functions correctly: abstract class AClass { protected sameTypeWithSingle ( x: any ): t ...

Error: Reference to an undeclared variable cannot be accessed. TypeScript, Cordova, iOS platforms

Can anyone offer some advice on what might be the issue? I'm encountering an error while building my Ionic app on the IOS platform, but everything is running smoothly on Android. ReferenceError: Cannot access uninitialized variable. service.ts:31 O ...

Managing events like onClick for custom components in Next.js and React: A Beginner's Guide

Utilizing tailwindCSS for styling and writing code in Typescript with Next.JS. A reusable "Button" component has been created to be used across the platform. When the button is pressed, I aim to update its UI in a specific way. For instance, if there&apos ...