Angular: Temperature Converter

Create a Temperature Converter component, as shown below:

The component should have the following functionalities:

  • It has 2 input number fields. The first is for a Celsius value, and the second is for a Fahrenheit value.

  • Initially, both fields are empty.

  • As a value is typed into the Celsius field, convert it to Fahrenheit and show it in the Fahrenheit field. Use the formula F = C*9/5 + 32 for conversion. In case of decimals, show up to 1 decimal value.

  • As a value is typed into the Fahrenheit field, convert it to Celsius and show it in the Celsius field. Use the formula C = (F − 32) × 5/9 for conversion. In case of decimals, show up to 1 decimal value.

The following data-test-id attributes are required in the component for the tests to pass:

  • The Celsius input should have the data-test-id attribute ‘celsius-input’.

  • The Fahrenheit input should have the data-test-id attribute ‘fahrenheit-input’.

Please note that the component has the above data-test-id attributes for test cases and certain classes and ids for rendering purposes. It is advised not to change them.

SOLUTIONS:

				
					<!-- temperatureConverter.component.html -->
<div class="layout-column align-items-center mt-50">
  <section class="layout-row align-items-center justify-content-between">
    <label>Celsius: </label>
    <input
      type="number"
      class="large"
      data-test-id="celsius-input"
      [(ngModel)]="c"
      (ngModelChange)="onChange($event, 'c')"
    />
  </section>

  <section class="layout-row align-items-center justify-content-between">
    <label>Fahrenheit: </label>
    <input
      type="number"
      class="large"
      data-test-id="fahrenheit-input"
      [(ngModel)]="f"
      (ngModelChange)="onChange($event, 'f')"
    />
  </section>
</div>

				
			
				
					// temperatureConverter.component.ts
import { Component, OnInit } from "@angular/core";

@Component({
  selector: "temperature-converter",
  templateUrl: "./temperatureConverter.component.html",
  styleUrls: ["./temperatureConverter.component.scss"],
})
export class TemperatureConverter implements OnInit {
  c = null; // Change the initial value to null
  f = null; // Change the initial value to null
  constructor() {}

  ngOnInit() {}

  onChange(value: string | null, type: "c" | "f") {
    if (value === null || value === "") { // Add a check for an empty string
      this.c = null;
      this.f = null;
      return;
    }

    const temperature = Number(value);
    if (type === "c") {
      this.f = ((temperature * 9) / 5 + 32).toFixed(1);
    } else {
      this.c = (((temperature - 32) * 5) / 9).toFixed(1);
    }
  }
}