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

How to pass data between components in Angular using @Input, @Output, and EventEmitter

After selecting a team from an array in one component, I am having trouble passing that selected team to another component. While I can log the selected team in the same component, I'm unable to access it in the other component. My goal is to use the ...

Utilizing a Material UI custom theme in React with Typescript: A step-by-step guide

Upon using the tool , I received a js file and a json file following the paths mentioned on the theme generator page: // src/ui/theme/index.js /* src/ui/theme/theme.json */ The files operate smoothly when left with the .js extension. However, when I attem ...

I want to use Angular and TypeScript to play a base64 encoded MP3 file

I am attempting to play a base64 encoded mp3 file in an Angular application. I have a byteArray that I convert to base64, and it seems like the byte array is not corrupted because when I convert it and paste the base64 string on StackBlitz https://stackbli ...

Child route CanActivate guards execute before the parent Resolve completes

I'm currently facing an issue with resolving data prior to navigating to child routes in order to utilize that data within the children guard. The problem lies in the fact that the parent resolver is executing after the child guard has already been tr ...

The process of invoking the AsyncThunk method within the Reducer method within the same Slice

Within my slice using reduxjs/toolkit, the state contains a ServiceRequest object as well as a ServiceRequest array. My objective is to dispatch a call to a reducer upon loading a component. This reducer will check if the ServiceRequest already exists in ...

Utilizing npm to execute scripts stored in a dedicated file

I am currently working on an Angular project that consists of multiple libraries. The project follows a plugin architecture where the goal is to build and serve each plugin on separate servers. As the number of plugins increase, my build:plugins script is ...

How can I access other properties of the createMuiTheme function within the theme.ts file in Material UI?

When including a theme in the filename.style.ts file like this: import theme from 'common/theme'; I can access various properties, such as: theme.breakpoints.down('md') I am attempting to reference the same property within the theme ...

What is the best way to retrieve the href attribute when working with cheerio?

Is there a way to retrieve the link using Cheerio in this code snippet? <div class="someClass"> <a href="someLink">Link</a> </div> I attempted to do so, but unfortunately it was unsuccessful. let link = $(&a ...

Youngster listens for guardian's occurrence in Angular 2

While the Angular documentation covers how to listen for child events from parents, my situation is actually the opposite. In my application, I have an 'admin.component' that serves as the layout view for the admin page, including elements such a ...

Issues arise in Typescript single-page applications due to the use of application insights

Currently, I am developing a single-page HTML application using TypeScript in VSCode. Initially, the app was running smoothly without any errors or warnings. However, I decided to incorporate Azure Application Insight into the project. To integrate it, I ...

Having trouble retrieving an array element within an HTML table

Currently, I am working on a database project related to bar beer drinkers. To display the results of my queries on a local host website, I am running queries on my database and using Angular. The issue I am facing is that while I can see the query executi ...

Creating a ref with Typescript and styled-components: A comprehensive guide

Trying to include a ref into a React component looks like this: const Dashboard: React.FC = () => { const [headerHeight, setHeaderHeight] = useState(0); const headerRef = React.createRef<HTMLInputElement>(); useEffect(() => { // @ts ...

Utilizing React and TypeScript: Passing Arguments to MouseEventHandler Type Event Handlers

Can you help me understand how to properly define the event handler handleStatus as type MouseEventHandler, in order to pass an additional argument of type Todo to the function? interface TodoProps { todos: Array<Todos> handleStatus: Mous ...

Creating a realistic typewriter effect by incorporating Code Block as the input

I am looking to add a special touch to my website by showcasing a code segment with the Typewriter effect. I want this code block not only displayed but also "typed" out when the page loads. Unfortunately, I have been unable to find a suitable solution s ...

Exploring Iteration of TypeScript Arrays in ReactJS

Issue Encountered: An error occurred stating that 'void' cannot be assigned to type 'ReactNode'.ts(2322) The error is originating from index.d.ts(1354, 9) where the expected type is related to the property 'children' defi ...

Two primary router outlets featuring unique layouts

Design for all users Design for staff members (such as admin control panel) I am using a router-outlet with the first design. How can I switch to the second design at "/personnel"? I want to keep both designs intact since "personnel" has its own componen ...

The index declaration file has not been uploaded to NPM

After creating a Typescript package and publishing it on NPM, I encountered an issue with the declaration files not being included in the published version. Despite setting declaration: true in the tsconfig.json, only the JavaScript files were being publis ...

Encountered a Build Error in Visual Studio 2019 while working on an Angular Application

Recently, I created an application using Angular 8 and .Net Core 2.2 (Web API) in Visual Studio 2019 (Community Edition). To streamline the project organization, I followed the guidelines provided in this informative link: Add angular 7.0 client applicatio ...

Tips for sequentially arranging and rearranging an array of numbers, even when duplicates are present

Encountered a perplexing issue that has me scratching my head in an attempt to visualize a solution. Currently, I am working with an array of objects that appears as follows: let approvers = [{order:1, dueDate: someDate},{order:2, dueDate: someDate}, ...

Encountered a Building Error: "The type .... is included in the declarations of two modules: AppModule and Ionic."

As I strive to generate my APK for Android, I executed the following command: ionic cordova run android --prod --release Version of Ionic being used: Ionic V3 My app currently does not employ lazy loading (I confess I am not even sure how to go about th ...