Search code examples
angulartypescriptangular-materialobservableangular-services

Angular 8 : How to do calculation on observable object's two properties and need to save on another property


I need to show sum of two properties of an observable data. here is my code Please advice me how to fix it.

Typescript class

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

In typescript service:

I have declared the observable object

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

In Component Class:

subscribed that observable Model in calcuation component

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

In component view :

In the view, Amount1 and Amount2 property are declared for inputs and total is displayed.

  <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>

I need to show the sum of Amount1 and Amount2 on Total property when ever we change the amount.

Thank you.


Solution

  • Please try

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