Retrieving the value of a variable within an object using an Observable

Can someone help me figure out how to assign a variable to a value inside an object in an Observable in my typescript file? I can retrieve the variable's value in my HTML file, but I seem to be missing something crucial. I believe the solution may involve two-way binding, but I haven't been able to get it working. Any assistance would be highly appreciated. Here is the code snippet:

import { Component, OnInit } from '@angular/core';
import { AppState } from '../store';
import { State, Store } from '@ngrx/store';
import { NgForm } from '@angular/forms';
import * as fromCurrencies from '../store/actions/currencies.actions';
import { Currency } from '../Models/currency';
import { Observable } from 'rxjs';
import * as fromSelectors from '../store/selectors/currencies.selectors';
import { selectCurrency } from '../store/selectors/currencies.selectors';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css'],
})
export class HomeComponent implements OnInit {
  constructor(private store: Store<AppState>) {}
  public currency$: Observable<Currency>;
  public conversionRate: number;
  public convertedAmount: number;
  ngOnInit(): void {}

  OnSubmit(form: NgForm) {
    console.log('currency: ' + form.value.symbol);
    this.store.dispatch(
      fromCurrencies.findCurrency({
        symbol: form.value.symbol,
      })
    );
    this.currency$ = this.store.select(fromSelectors.selectCurrency);
    this.convertedAmount = form.value.amount * this.conversionRate;
  }
}

The interface:

  id: number;
  symbol: string;
  name: string;
  conversionRate: number;
}

I need to set the value of the conversionRate within the Currency object to the variable conversionRate in the typescript file. I also have the related HTML code where I can retrieve the value.

<div>
  <form #form="ngForm" (ngSubmit)="OnSubmit(form)">
    <div class="currency-type">
      <label for="symbol">Symbol</label>
      <input
        type="text"
        name="symbol"
        ngModel
        required
        id="symbol"
        class="form-control"
        placeholder="enter symbol"
      />
    </div>
    <div>
      <label for="amount">Amount (€): </label>
      <input
        type="number"
        name="amount"
        ngModel
        required
        id="amount"
        class="form-control"
        placeholder="enter amount"
      />
    </div>
    <button
      type="submit"
      [disabled]="form.invalid"
      class="btn btn-primary btn-lg btn-block"
    >
      <span>Calculate Currency</span>
    </button>
  </form>
</div>

<table *ngIf="currency$ | async as currencyInfo">
  <thead>
    <tr>
      <th>Symbol</th>
      <th>Name</th>
      <th>Conversion Rate</th>
      <th>Amount (Euro)</th>
    </tr>
  </thead>
  <tr *ngFor="let curr of currencyInfo">
    <td>{{ curr.symbol }}</td>
    <td>{{ curr.name }}</td>
    <td>{{ curr.conversionRate }}</td> //value I want to assign in ts file
    <td>{{ conversionRate }}</td>
  </tr>
</table>

Edit: I managed to resolve this issue by incorporating a for loop inside the table within the form. This allows me to define a select tag equal to the value. Below is the updated HTML code:

<div *ngIf="currency$ | async as currencyInfo">
  <form #form="ngForm" (ngSubmit)="OnSubmit(form)">
    <div class="currency-type">
      <label for="symbol">Symbol</label>
      <input
        type="text"
        name="symbol"
        ngModel
        required
        id="symbol"
        class="form-control"
        placeholder="enter symbol"
      />
    </div>
    <div>
      <label for="amount">Amount (€): </label>
      <input
        type="number"
        name="amount"
        ngModel
        required
        id="amount"
        class="form-control"
        placeholder="enter amount"
      />
    </div>
    <div>
      <label>Conversion Rate:</label>
      <select
        *ngFor="let curr of currencyInfo"
        name="rate"
        type="number"
        id="rate"
        ngModel
        class="form-control"
        value="{{ curr.conversionRate }}"
        id="rate"
      >
        <option>
          {{ curr.conversionRate }}
        </option>
      </select>
    </div>
    <button
      type="submit"
      [disabled]="form.invalid"
      class="btn btn-primary btn-lg btn-block"
    >
      <span>Calculate Currency</span>
    </button>
  </form>
</div>

<table *ngIf="currency$ | async as currencyInfo">
  <thead>
    <tr>
      <th>Converted Amount</th>
    </tr>
  </thead>
  <tr *ngFor="let data of currencyInfo">
    <td>{{ convertedAmount }}</td>
  </tr>
</table>

Answer №1

To update the curr.conversionRate, you can utilize an input element and bind it using [(ngModel)] as shown below =>
HTML:

<tr *ngFor="let info of currencyData">
    <td>{{info.name}}</td>
    <td>
        <tr>
            <input type="number" (ngModelChange)="updateData(info,$event)" [(ngModel)]="info.conversionRate">
        </tr>
    </td>
    <td>{{info.conversionRate }}</td>
</tr>

TS:

updateData(info,$event){
   //console.log(info);
   //console.log($event);
  }

Note: Here is a live demo link for reference => Stackblitz Demo.

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

End of container Bootstrap 4 row with two columns at the edge

I'm currently working on an angular project with bootstrap 4. Within the container, there are two rows. I specifically want one row to always be positioned at the bottom of the container. Despite trying methods like justify-content: flex-end;, botto ...

The process of incorporating the dymo.framework into an Angular project

My Angular project is currently in need of importing dymo.connect.framework. However, I am facing some challenges as the SDK support provided by dymo only explains this process for JavaScript. I have also referred to an explanation found here. Unfortunate ...

Error: The absence of an element identified by the locator does not cause the protractor spec to fail, but rather it executes successfully

This automation framework follows the page object model and utilizes the async/await approach rather than promises. TypeScript is used, with compilation to JavaScript (protractor) for script execution. Page Object: async addProjectDetails(): Promise< ...

updating an object using its instance in angular: step-by-step guide

Having multiple nested arrays displaying data through HTML recursion in Angular, I am faced with the task of updating specific fields. Directly editing a field is simple and involves assigning its instance to a variable. arr=[{ "name":"f ...

The CommonsChunkPlugin in Webpack and leveraging the "import * as" syntax

I've been studying Webpack for a while now and recently encountered an unusual issue. According to the Webpack Introduction on angular.io, I organize my vendor modules in the vendor.ts file, polyfills in the polyfill.ts file, and initialize my app in ...

Troubleshooting problem with the ng2-dragula drop container

Continuation of the inquiry from the discussion on ng2-dragula setOptions and drop version problem. My current workaround involves using a placeholder to address the issue of an empty container. I suspect that the approach I am currently employing, such a ...

What is the source of Docker's node version information?

Within the Dockerfile, I specified the version node:14.17.6-alpine3.13. However, in the deployment log, it shows a different version, node:16.13.2-alpine. Can anyone shed light on why this discrepancy exists and how to rectify it? docker-compose deploy lo ...

What is the process for importing string data into an Excel document using Angular?

I'm encountering a situation where I have non-JSON data coming from the backend. How can I efficiently write this type of data into an Excel file? To handle this task, I've utilized XLSX and FileSaver libraries by referencing an example on Plunk ...

The Tanstack react-table feature is limited in its ability to output tsx from the cell

Currently conducting a test on Tanstack react-table library using React and TypeScript. It appears that I am encountering an issue with returning tsx/jsx from the cell function of ColumnDef: https://i.sstatic.net/d5X3y.png Is there something crucial that ...

One function in Typescript lodash is missing a default export

Is there a way to import just one function from lodash? I attempted it like this: import get from 'lodash/get'; Even after installing both lodash and @types/lodash, I encountered the following error message: @types/lodash/get/index"' ha ...

Object data is not being received by the defaultValue in React Hook Form

I am currently utilizing React Hook Form to facilitate the process of editing/updating data. I retrieve my data from zustand with a value type of any, and then proceed to save it as the defaultValue in React Hook Form. However, when attempting to acquire v ...

Tips for remembering to reactivate the Protractor Angular synchronization feature

Our test codebase is quite large, with around 10,000 lines of JavaScript code. In certain situations, we find it necessary to disable Protractor-to-Angular synchronization using the following line of code: browser.ignoreSynchronization = true; However, o ...

Is there a way to implement hover behavior for a Material-UI Button within a ButtonGroup component?

When using MUI v5, I am encountering an issue where the first button in the code provided is only half working. The button is initially colored red (both the border and text), however, upon hovering over it, the color of the border changes to blue. This is ...

In Angular 11, the error message "Type 'Object' cannot be assigned to type 'NgIterable<any> | null | undefined'" is appearing

Struggling to grasp the concepts of Angular and TypeScript for the first time, particularly puzzled by why this code snippet is not considered valid! http.service.ts export class HttpService { constructor(private http: HttpClient) { } getBeer() { ...

The error message "Unable to access 'useContext' property of null" appeared

I am currently in the process of developing a component library using Material UI, TypeScript, and Rollup. The package has been successfully published, but I am encountering an error when trying to import it into a new project: "Uncaught TypeError: C ...

Steps for initiating an Angular 4 project

While most developers have moved on to Angular 5, I was tasked with creating a project using Angular 4. After conducting research for several days, I discovered that downgrading the Angular CLI would allow me to accomplish this. By following this approach, ...

Trapped in a Continuous Observing Loop with MdSnackBar in Angular Material within Angular 2

Whenever my login attempt fails, I want to display a snackbar with the message 'error connecting'. After dismissing the snackbar, I would like the login to be retried after 10 seconds. However, I'm facing an issue where my observable is runn ...

Fastify Schema Failing to Validate Incoming Requests

Currently, our backend setup involves using Node.js and the Fastify framework. We have implemented a schema in satisfy to validate user input. Below is the schema defined in schema.ts: export const profileSchema = { type: 'object', properti ...

Tackling the white-source security problem in npm libraries

A security advisory from White-source has identified high vulnerability issues with certain libraries used in your repository, specifically with yargs-parser: 1. build-angular-0.13.8.tgz (Root Library) node-sass-4.11.0.tgz sass-graph-2.2 ...

Issue with for loop execution within subscribe event

In my chat design, there is a list of people on the left side. When a user clicks on any person, I display their chat history on the right side. To achieve this, I need to transfer user details from one component to another using an RXJS subscribe call. Da ...