The art of connecting models in Angular 2

Hey there! I've got a setup that seems to be giving me some unexpected results. Whenever I make changes to either the Kelvin or Celsius field, I end up with strange outputs like multiplying by 1000 or other inexplicable numbers. I'm new to Angular 2, so I'm thinking it might have something to do with how I set up the binding.

Can anyone lend a hand? Any help would be greatly appreciated!

class Temperature {
  kelvin: number;

  constructor(kelvin: number) {
    this.kelvin = kelvin;
  }

  getKelvin(): number {
    return this.kelvin;
  }

  setKelvin(kelvin: number) {
    this.kelvin = kelvin;
  }

  getCelsius(): number {
    return this.kelvin - 273.15;
  }

  setCelsius(celsius: number) {
    this.kelvin = celsius + 273.15;
  }
}

export class ConverterComponent implements OnInit {
  temperature: Temperature;

  constructor() {
    this.temperature = Temperature.fromKelvin(21);
  }

  onKelvinChange(kelvin: number) {
    this.temperature.setKelvin(kelvin);
  }

  onCelsiusChange(celsius: number) {
    this.temperature.setCelsius(celsius);
  }


<input id="temperature-kelvin" type="number" class="form-control" [ngModel]="temperature.getKelvin()" (input)="onKelvinChange($event.target.value)" />
<input id="temperature-celsius" type="number" class="form-control" [ngModel]="temperature.getCelsius()" (input)="onCelsiusChange($event.target.value)" />

Answer №1

Implement the code below. There's no need for [(ngModel)] as the input value is captured in Onchange.

Temperature Converter

class Temperature {
  kelvin: number;

  constructor() {

  }

  getKelvin(): number {
    return this.kelvin;
  }

  setKelvin(kelvin: number) {
    this.kelvin = kelvin;
  }

  getCelsius(): number {
    return this.kelvin - 273.15;
  }

  setCelsius(celsius: number) {
    this.kelvin = celsius + 273.15;
  }
}

Component File

export class ConverterComponent implements OnInit {
  temperature: Temperature;

  constructor() {
    this.temperature = new Temperature();
  }

  onKelvinChange(event) {
    this.temperature.setKelvin(event.target.value);
  }

  onCelsiusChange(event) {
    this.temperature.setCelsius(event.target.value);
  }

HTML Template

<input id="temperature-kelvin" type="number" class="form-control" (keyup)="onKelvinChange($event)" />
<input id="temperature-celsius" type="number" class="form-control" (keyup)="onCelsiusChange($event)" />

Answer №2

After some investigation, I managed to find the solution to my problem, although it did make me feel a little sheepish. It turns out that Typescript doesn't handle method parameters in a type-safe way when translating to JS. This led to a misunderstanding in the method below, where instead of adding numbers, it was concatenating strings because the celsius parameter was being treated as a string from the input field.

setCelsius(celsius: number) {
  this.kelvin = celsius + 273.15;
}

Fortunately, this issue can be easily rectified by using the unary operator + in front of the variable like so:

setCelsius(celsius: number) {
  this.kelvin = +celsius + 273.15;
}

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

Mat backspin dialogue spinner

Our current setup involves using a progress spinner for each API call. The spinner is registered at the app module level, but we are facing an issue where the spinner hides behind the dialog popup. In order to solve this problem, we have decided to includ ...

Angular encountering issues with loading external JavaScript files due to the error: ENOENT - indicating that the specified file or directory does

I am attempting to incorporate a bootstrap template into Angular. The template requires some external JavaScript and CSS files that need to be linked. I have placed these files in the assets folder and referenced them in the styles and scripts arrays of an ...

How to handle an already initialised array in Angular?

I came across an interesting demo on exporting data to Excel using Angular 12. The demo can be found at the following link: This particular example utilizes an array within the component TypeScript file. import { Component } from '@angular/core' ...

Navigating Timezones with PrimeNG Calendar Component <p-calendar>

I am experiencing an issue with PrimeNG in a multi-user environment where each user is in a different timezone. I need all users to submit their form data in EST, but it seems like the browser is converting the dates to the user's local timezone upon ...

What is the reason behind the slight difference between TypeScript's IterableIterator<> and Generator<> generics?

In TypeScript version 3.6.3, there is a notable similarity between Generator<> and IterableIterator<>. However, when Generator<> extends Iterator<>, the third generic argument (TNext) defaults to unknown. On the other hand, Iterator ...

Resolve the issue of text overflow in PrimeNG Turbo Table cells

When utilizing Primeng table and enabling the scrollable feature, the table is expected to display a scrollbar while ensuring that the text within the cells does not overflow. Unfortunately, this expected behavior is not occurring. To see an example of th ...

Ways to incorporate debounce time into an input search field in typescript

Is there a way to incorporate debounce time into a dynamic search box that filters data in a table? I have explored some solutions online, but my code varies slightly as I do not use throttle or similar functions. This is my template code: <input matI ...

Guide to dynamically assigning attribute values in Angular 7 based on specific conditions

I've been attempting to dynamically set the value of the data-color attribute for my <li> tag based on a specific condition. Here's a sample array containing the data I need to check: { Notifications: [ { notification: "Example Notificatio ...

Error: ChangeDetectorRef provider is missing from the NullInjector

Implementing Angular 5, I have encountered an error while attempting to trigger a function called select() in one component for selection purposes. This function then triggers another function named getqr() in a separate component responsible for printing. ...

When using Google Maps, be sure to load it carefully as it may appear gray on the second attempt

After developing an Ionic 2 / Angular 2 App with integrated Google Maps, I encountered a problem. The second time the Google Maps loaded, it appeared completely gray. Despite trying various solutions found online such as triggering 'resize' event ...

What makes using the `@input` decorator more advantageous compared to the usage of `inputs:[]`

In defining an input on a component, there are two available methods: @Component({ inputs: ['displayEntriesCount'], ... }) export class MyTable implements OnInit { displayEntriesCount: number; Alternatively, it can be done like this ...

Confirm button title by verifying part of the label that contains a space

I'm facing an issue with clicking a button using the following code: await page.getByRole('button', { name: '3 Employees' }).click(); The problem is that the button's name fluctuates based on the number of employees, causing ...

Angular2 is throwing an error: "NavigationService provider not found! (MenuComponent -> NavigationService)"

I am in the process of developing an angular (beta7) application. I aim to have a MenuComponent at the top that utilizes the NavigationService to navigate throughout different sections of my app. To ensure that the NavigationService remains a singleton, I ...

Guide to adding Angular 2 components to various locations in the DOM of a vanilla JavaScript webpage

Scenario: A customer is interested in creating a library of Angular 2 components that offer a technology-agnostic interface to developers. This allows developers to use plain JavaScript without needing knowledge of the internal workings of the library. Th ...

Can you explain the process for accessing a parent function in Angular?

I have a form component that inserts data into a database upon submission, and I need to update the displayed data in another component once it changes in the database. I attempted using ViewChild to invoke the necessary functions, but encountered issues w ...

Creating reducers for a unique data type: A step-by-step guide

Today, I was working on enhancing a shopping website using React Typescript and Context API. My goal is to utilize React Reducers to manage the state of my Shopping Cart. I have custom Types defined for the Product type, which includes an Items Array and s ...

Angular 2 Aot Issue: CRITICAL ERROR: CALL_AND_RETRY_LAST Allocation unsuccessful - JavaScript heap exhausted

Encountered an issue while running Angular 2 AOT rollup: <--- Last few GCs ---> 144518 ms: Mark-sweep 1317.0 (1404.4) -> 1317.0 (1404.4) MB, 1522.9 / 0.0 ms [allocation failure] [GC in old space requested]. 146029 ms: Mark-sweep 1317.0 (1404 ...

Changing the time in Angular while converting a string to a date object has proven to be

Can anyone help me with a problem I'm having trying to convert a String into a Date object without it being affected by timezone changes? Specifically, when I receive 2020-07-14T15:27:39Z from an http get request, I need to convert this into a Date o ...

Sharing API types from a NestJs backend to a Vue frontend (or any other frontend) application: Best practices

In my development setup, I have a VueJs and Typescript Front End app along with a PHP server that is in the process of being converted to NestJs. Both of these projects reside in the same Monorepo, allowing me to share types for DTOs between them. I am ex ...

Tips for avoiding the push method from replacing my items within an array?

Currently, I am diving into Typescript and VueJS, where I encountered an issue with pushing elements to my array. It seems to constantly override the 'name' property. Let me share the code snippet causing this problem: const itemsSelectedOptions ...