I'm attempting to utilize a service function in Angular 9 that converts Celsius to Kelvin based on user input from a text field. I have defined a function that takes the Celsius degrees as input and computes the equivalent Kelvin by adding 273.15. However, instead of performing the calculation correctly, it seems to concatenate the values on the front end. Upon testing the code, I discovered that it returns a string even though I expected it to be a number. By explicitly casting the input as a number, I was able to resolve the issue. Can someone provide insight into why the input type did not cause the call to fail or at least perform a dynamic cast?
public convertCToK(celsius: number): number { // e.g. celsius = 1
console.log(typeof celsius); // returns 'string'
// return celsius + 273.15; returns 1273.15
return Number(celsius) + 273.15; // returns 274.15
}
The following snippet shows the calling function and HTML:
fahrenheit: number;
celsius: number;
kelvin: number;
changeC() {
if (!isNaN(this.celsius)) {
this.fahrenheit = Math.round(this.calcService.convertCToF(this.celsius) * 100) / 100;
this.kelvin = Math.round(this.calcService.convertCToK(this.celsius) * 100) / 100;
}
}
<h2>Fahrenheit:
<label>
<input style="color:green" type='text' [(ngModel)]='fahrenheit' (keyup)="changeF()">
</label>
</h2>
<hr>
<h2>Celsius:
<label>
<input style='color:blue' type='text' [(ngModel)]="celsius" (keyup)="changeC()">
</label>
</h2>
<hr>
<h2>Kelvin:
<label>
<input style="color:red" type='text' [(ngModel)]='kelvin' (keyup)="changeK()">
</label>
</h2>