I'm trying to call a service function in Angular 9 from input in a text field to convert Celsius to Kelvin. I specified one function that takes in the degrees in Celsius, in order to compute to Kelvin by adding 273.15. Instead, it concatenates on the front end instead. I tested the code and sure enough it returns string, after just accepting it as number. Casting as a number resolves the issue, but can anyone help me understand why typing didn't fail the call or at the least cast it on the fly?
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 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>