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.