Is there a way to automatically populate the result input field with the dynamic calculation results from a dynamic calculator in Angular6?

My current challenge involves creating dynamic calculators with customizable fields. For example, I can generate a "Percentage Calculator" with specific input fields or a "Compound Interest" Calculator with different input requirements and formulas. Successfully, I have managed to develop these dynamic calculators.

In my setup, there are 2 key components - the HomeComponent and the CalculatorComponent. The CalculatorComponent is called within the HomeComponent, passing JSON data from home.component.ts like this:

this.dynamicFormJson = {
  heading : 'Percentage Calculator',
  totalFields : 3,
  inputs : [
    {label : 'Percent', placeholder : 'Enter Percentage Here', type : 'number', variable : 'percent'},
    {label : 'Amount', placeholder : 'Enter Amount Here', type : 'number', variable : 'amount'},
    {label : 'Result', placeholder : '', type : 'number', variable : 'res'}
  ]
}

The code in my calculator.component.ts file involves dynamic creation of variables for each input field, which are then bound to the dynamically created input fields.

import { Component, OnInit , Input} from '@angular/core';

@Component({
 selector: 'app-calculator',
 templateUrl: './calculator.component.html',
 styleUrls: ['./calculator.component.css']
 })
export class CalculatorComponent implements OnInit {

 @Input() formJson : any;
 formInputsVar = {};
 constructor() { }

 ngOnInit() {
 this.formJson.inputs.map((item : any)=>{
  if (!this.formInputsVar[item.variable]) {
    this.formInputsVar[item.variable] = '';
  }
 })
}
 onSubmit(){
  console.log(this.formInputsVar);
 }

} 

This approach allows me to create dynamic calculators, generate variables for input fields, and capture values upon submission through the onSubmit event. You can view the complete working code on StackBlitz.

I am now exploring how to implement formulas that automatically calculate results in real time as users input values. Each calculator will have its own JSON data and formula specifications, making it challenging to implement dynamic formulas for various calculators.

If the formula is included in the JSON object of the calculator, such as:

this.dynamicFormJson = {
  heading : 'Percentage Calculator',
  totalFields : 3,
  inputs : [
    {label : 'Percent', placeholder : 'Enter Percentage Here', type : 'number', variable : 'percent'},
    {label : 'Amount', placeholder : 'Enter Amount Here', type : 'number', variable : 'amount'},
    {label : 'Result', placeholder : '', type : 'number', variable : 'res'}
  ],
formula : "percent * amount / 100"
}

I need guidance on implementing these formulas dynamically in my generated calculators.

Please Note: Every calculator will have unique JSON structure and formula requirements.

You can observe a similar calculator functionality on a reference website.

I aim to replicate the same interactive calculator experience. Feel free to explore other calculators on the reference site. I am employing Angular6 for this project.

Answer №1

Great question! To achieve the desired outcome on your stackblitz, simply make these two modifications:

Here are some key points to consider:

  • The calculator can accommodate any number of fields.
  • I assume that the operator is set to multiplication. To use a different operator, adjust it within the loop in the function updateResult. For complete flexibility, you could also allow users to input the operator.
  • The final item in your dynamicFormJson serves as the location for storing the calculated result. This explains why we loop from 0 to this.formJson.inputs.length-1.

Added an updateResult() function in calculator.component.ts. Here's the full code snippet:

import { Component, OnInit, Input} from '@angular/core';

@Component({
  selector: 'app-calculator',
  templateUrl: './calculator.component.html',
  styleUrls: ['./calculator.component.css']
})
export class CalculatorComponent implements OnInit {

  @Input() formJson : any;
  formInputsVar = {};
  constructor() { }

  ngOnInit() {
    this.formJson.inputs.map((item : any)=>{
      if (!this.formInputsVar[item.variable]) {
        this.formInputsVar[item.variable] = '';
      }
    })
  }

  updateResult(){
    var tempMultiplicationValue =1;
    for(var i=0; i<this.formJson.inputs.length-1; i++){
      tempMultiplicationValue = tempMultiplicationValue * this.formInputsVar[this.formJson.inputs[i].variable];
    }
    this.formInputsVar['res'] = tempMultiplicationValue;
  }


  onSubmit(){
    console.log(this.formInputsVar);
  }

}

Added (change)="updateResult()" in calculator.component.html. Here's the updated HTML code:

<div class="row">
  <div class="col-md-6">
    <form style="margin:100px 0 0 100px;background-color: lightgrey; padding: 20px;">
      <h2>{{formJson.heading}}</h2>
      <div class="form-group" *ngFor="let inputRow of formJson.inputs">
        <label for="exampleInputEmail1">{{inputRow.label}}</label>
        <input type="{{inputRow.type}}" class="form-control"  [(ngModel)]="formInputsVar[inputRow.variable]" [ngModelOptions]="{standalone: true}" (change)="updateResult()" aria-describedby="emailHelp" placeholder="{{inputRow.placeholder}}">
      </div>
      <button type="submit" class="btn btn-primary" (click)="onSubmit()">Submit</button>
    </form>
  </div>
</div>

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

When utilizing React router v5, the exact property in a route may not function as expected if there is a

I am attempting to structure routes like Vue.js in an array format: // routes.js export const routing = [ { path: "/setting", component: Setting, }, { path: "/", co ...

Sending data with POST or PUT requests in HttpClient is a

I'm currently attempting to update my database in my client application using a PUT/POST method with HttpClient. Which of the following methods is more correct, and why are neither of them working? First: HTTP/1.1 415 Unsupported Media Type List ...

Internal server error frequently occurs when there is an issue with Ajax requests in a Laravel application

Greetings, fellow developers! I am encountering an issue with the comments system in Laravel and Ajax. While it functions correctly with PHP alone, I am facing difficulties when using Ajax. The error message I am receiving is as follows: Status Code:50 ...

I'm trying to figure out how to redirect only the empty path using the new router in Angular 2. Can anyone

Environment: Upgraded to RC4 with brand new router Here is the current configuration of my router.. export const routes: RouterConfig = [ {path: 'search-documents', component: SearchDocumentsComponent}, { path: '', pathMat ...

Parse through a JSON input and generate a hierarchical treeview structure using the specified keys, while also considering any child keys present

Can someone assist me with the code snippet below? JObject my_obj = JsonConvert.DeserializeObject<JObject>(ReceivedJson); ParseJson(my_obj); //method to store all the nested "keys" and the "id" values public void ParseJson(JObject obj) ...

I am interested in implementing a logout feature using a button in PHP

<?php session_start(); ?> <form> <input type="button" id="logout" value="logout" name="logout"> </form> After initializing the session during login, I am seeking to terminate it using a button rather than via <a href="">l ...

Material-UI React Native components: Injecting Styles without Props

import {createStyles, WithStyles} from "@material-ui/core"; const styles = (theme: Theme) => createStyles({ root: {} }); interface MyProps extends WithStyles<typeof styles> { } export class MyComponent extends Component<MyProps ...

The mat select option does not have the correct width for the mat

Can someone please help me with this issue? I'm having trouble with the width of the options in a mat-select within a form. When I try to select an option, the width extends to 100% instead of staying within the select box. Here is a snapshot showing ...

Incapable of modifying the text within a div container

I am currently working on a script that translates a Russian forum word by word using TreeWalker. However, there is a specific type of div element that I have been unable to change the text for. That leads to my question: How can I go about changing it? Un ...

Tips for minimizing the padding/space between dynamically generated div elements using html and css

Currently, I have 4 dropdown menus where I can choose various options related to health procedures: Area, specialty, group, and subgroup. Whenever I select a subgroup, it dynamically displays the procedures on the page. However, the issue I am facing is th ...

What is the reason for function components running in multiples of 2 when the state changes?

I need help with a React question that I can't quite figure out. I have a component where new data keeps getting added to the existing data. Initially, it makes sense for two console logs to appear due to Mount and Update. But after that, why do 4 con ...

Searching for a solution to eradicate and " from a JSON value in Apache Nifi?

After invoking the Rest API, I received a JSON flowfile response which includes data on different offers: { "data": [ { "description": "\n\n\"s, lorem Epsom jdfg\n\"", " ...

The application of Angular's extension may experience functionality issues due to a failed ngcc operation

https://i.stack.imgur.com/Q7eFX.png The current issue I am encountering. https://i.stack.imgur.com/Kj1r0.png However, the command ng serve is functioning smoothly without any errors. https://i.stack.imgur.com/0SluL.png I'm also facing this partic ...

What is the best method to completely uninstall Apollo-Angular along with all of its dependencies?

Once I added apollo-angular and @apollo/client to my project, I quickly realized that I no longer needed them. However, simply using "npm uninstall apollo-angular" and "npm uninstall @apollo/client" only removed the main folders but left behind other Apoll ...

What could be causing this JavaScript to output undefined?

const urls = [ "http://x.com", "http://y.com", "http://z.com", ]; for (let j=0; j<urls.length; j++) { setTimeout(function() { console.log(urls[j]); }, 3000); } I'm inserting this code snippe ...

The JavaScript code is attempting to execute a PHP script, however, I am struggling to parse the JSON data returned for use in the

As a novice, I am in the process of creating a JavaScript function that calls a PHP script every second. The PHP script retrieves values from MySQL DB, encodes them into JSON, which is then decoded by JS to display them on an HTML page. I have two queries ...

Incorporating unique symbols into a RegExp object during its creation using a variable

As a beginner, I am currently working on a small function that will allow users to pick up objects and add them to an inventory by entering text in a box. In my setup, there is a text box with the id "commandBox" and a button that triggers the 'pickU ...

Determine the full location information with the help of Google Maps SDK without the need

My current challenge involves dealing with a list of unformatted and incorrectly written addresses. I am seeking a way to iterate through these flawed strings and generate more organized and accurate addresses using one of the many Google Maps SDKs availa ...

Removing error messages upon form reset initiated by an API request

Is there a way to clear error messages that appear beneath a text field when resetting form fields with values from an api call? In my Formik form, I have three fields that are loaded from an api database call along with a Reset button that reloads these ...

Identifying a failed Ajax Request in JavaScript

How can I check if an Ajax request failed to load a file? Here is the code I'm currently using: var pro = undefined; var xmlhttp; if (window.XMLHttpRequest){ xmlhttp = new XMLHttpRequest(); } else{ xmlhttp=new ActiveXObject("Microsoft.XMLHTT ...