Performing calculations on two properties of an observable object in Angular 8 and then storing the result in a new property

Looking for guidance on how to display the sum of two properties from an observable data. Take a look at the code below and let me know your thoughts:

Typescript class

export class Amount {
Amount1: number;
Amount2: number;
Total:number;
}

In typescript service:

I have created an observable object

export class AmountService {    
 public newmessageService = new BehaviorSubject(new Amount());    
  public Model = this.newmessageService.asObservable();     
}

In Component Class:

Subscribed to the observable Model in the calculation component

export class Calculation implements OnInit {    
Model$:Amount;     
  ngOnInit() {    
    this.service.Model.subscribe(temp => this.Model$ = temp)
  }
}

In component view :

The view includes inputs for Amount1 and Amount2 properties, with Total displayed below.

  <form name="calculationform">

  <mat-form-field class="example-full-width">    
    <mat-label>Amount1</mat-label>    
    <input matInput [(ngModel)]="Model$.Amount1" name="Amount1">    
  </mat-form-field>

  <mat-form-field class="example-full-width">    
    <mat-label>Amount2</mat-label>    
    <input matInput [(ngModel)]="Model$.Amount2" name="Amount2">    
  </mat-form-field>

      <mat-label>Total:</mat-label>        
      <mat-label>{{Model$.Total}}</mat-label>
</form>

Currently seeking a way to automatically update the Total property based on changes in Amount1 and Amount2.

Your assistance is greatly appreciated.

Answer №1

One option to explore is transforming the Total attribute into a getter method.

export class Amount {
  Amount1: number;
  Amount2: number;
  get Total():number {
    return this.Amount1 + this.Amount2;
  };
}

Answer №2

Give it a shot

ngDoCheck( ){
   this.service.Model.subscribe(result => {
      this.data$ = result;
      this.data$.Total = Number(this.data$.Amount1) + Number(this.data$.Amount2);
   });
}

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

Having trouble getting combineLatest to properly normalize data in Angular using RxJS

Difficulty arose when attempting to normalize data prior to merging it into a new stream, resulting in no changes. I need to verify whether the user has liked the post using a Promise function before including it in the Posts Observable. this.data$ = comb ...

Troubleshooting a Pulumi script in Azure using Typescript and encountering difficulties with function writing

My background is in using terraform, but now I am trying out Pulumi/typescript for the first time. In my codebase, I have two files - index.ts and blob.ts. The create function in blob.ts is responsible for creating a storage account, resource group, blob ...

Struggling to add phantom-js to my Angular project

I'm looking to incorporate the phantomJS library into my Angular 4 project for continuous integration with Jenkins. No matter what method I try, I keep encountering the same (or similar) error. For instance, when following this tutorial and attemptin ...

Angular 7 automatically updates array values with the most recent values, replacing any previous values in the process

Currently, I'm working with arrays and utilizing the map function to modify the data. Below is an array of icons: private socialIcons:any[] = [ {"icon":"thumbs-up","operation":"like"}, {"icon":"thumbs-down","operation":"unlike"}, {" ...

Using TypeScript along with the "this" parameter

Hi there, I'm encountering an issue with the code snippet below. It keeps throwing an error message that says "Property 'weatherData' does not exist on type 'XMLHttpRequest'." The purpose of this code is to display weather informat ...

Assign variable data to properties within an immutable object within a React component

I have declared a Const in my config.service.ts file like this: export const mysettings={ userid:"12324", conf:{ sessionDuration:30, mac:"LON124" } } I am using this constant in various components. However, instead of hardcoding these val ...

The ngFor directive seems to be malfunctioning as it is only displaying a single element from the object instead of iterating through all of them in Angular version 12

I'm having trouble looping through my array of objects in the UI. Only one element is being displayed. Can anyone help me figure out what I'm doing wrong? Here is my component.html file: <div class="card" *ngFor="let regionList ...

Angular2's integration of backend API calls

My backend calls are functioning correctly, but I'm encountering an issue with promises. I am unable to retrieve the data from the first promise in order to make the second call. Any insights on where I might be going wrong? login() { if (thi ...

The problem of package related to scrolling header in Ionic arises when building with the `--prod` flag (Remember to include a @NgModule annotation

Hey there! I stumbled upon a package in the git repository that seems to have everything set up for compatibility with AOT. However, when attempting to build my app using the ionic build --prod command, the AOT build encounters an error as displayed below. ...

What is the best way to send a search parameter to a URL?

In my asp.net core web api, I developed a method that generates an object with the string provided in the URL. I now have a search form that needs to pass this string to the URL and retrieve the objects containing it. Here is how I utilize the api: impo ...

Determine the data type of the value for the mapped type

Is there a way to access the value of a type like the following: interface ParsedQs { [key: string]: undefined | string | string[] | ParsedQs | ParsedQs[] } I am looking for a method to retrieve the ParsedQsValue type without directly duplicating it from ...

What is the syntax for passing a generic type to an anonymous function in a TypeScript TSX file?

The issue lies with the function below, which is causing a failure within a .tsx file: export const enhanceComponent = <T>(Component: React.ComponentType<T>) => (props: any) => ( <customContext.Consumer> {addCustomData => ...

What is the best way to ensure the hamburger menu stays perfectly centered?

My menu is currently aligned to the right and scrolls with the user profile. I want the menu to always be centered and the profile to stay on the right side. I am working with Angular 12 and Bootstrap 5 for this project. Here is the code I have been usin ...

The error message states that the property 'registerUser' is not found on the class 'UserController'

In the controller file, I exported two functions (registerUser and loginUser) as default. No errors were thrown at that stage, but when attempting to access the routes, an error occurred stating - Property 'registerUser' does not exist on type &a ...

Can we improve the coding of this as it seems inefficient and uses up too much room?

Do you think there is a more efficient way to write this code? It seems quite impractical and takes up a lot of space. Essentially, it's about the random chance of obtaining a rarity, like acquiring an Uncommon sword. if (Math.random() * 100 < 100 ...

Creating a downloadable text file in Angular

I need help with including data retrieved from an API GET call into a text file within my project. I have successfully called the API, displayed the data on the console and the webpage, but now I am struggling to save this data into a text file. Below is t ...

The error message "The file 'environment.ts' is not located within the specified 'rootDir' directory" was encountered during the Angular Library build process

When attempting to access the environment variable in an Angular 9 library, I encountered an error during the library build process. Here is how it was implemented: import { EnvironmentViewModel } from 'projects/falcon-core/src/lib/view-models/envir ...

Angular Universal: Missing Title and Meta tags in Page Source

I need help with updating title and meta tags in my Angular Universal Application after a successful api call. app.component.ts import {Component, Inject, OnInit, PLATFORM_ID} from '@angular/core'; import {Meta, Title} from '@angular/platfo ...

Can sweetalert2 be used as a tooltip?

I have a query, is it feasible to include a tooltip in the alert message? Alternatively, could there be another tooltip option available? Swal.fire({ title: '<strong>An example with HTML tags</strong>', icon: 'info', ...

Leveraging the unique operator with an observable

I've been attempting to eliminate duplicates from my observable by using .distinct(), but it doesn't seem to be working as expected. There are no errors showing either... this.settingsService.getGuruQueries().subscribe(queries => { of<an ...