Search code examples
htmlcssangulartypescriptangular-template

How to pass and display Calculation result on a New view/component in Angular?


I created a simple calculator app. I have two component: Calculator and Result and use Angular router between them. Now I want to do this : When I perform a calculation in Calculation component, the result will be passed and displayed in another Result component. Can you show me some ways for this ? enter image description here

enter image description here

calculator.component.ts


@Component({
  selector: 'app-calculator',
  templateUrl: './calculator.component.html',
  styleUrls: ['./calculator.component.css']
})
export class CalculatorComponent implements OnInit {

  public number1: number;
  public number2: number;
  public result: number;

  constructor() {
  }

  sum() {
    this.result = this.number1 + this.number2;
  }

  diff() {
    this.result = this.number1 - this.number2;
  }

  mult() {
    this.result = this.number1 * this.number2;
  }

  divi() {
    this.result = this.number1 / this.number2;
  }

  ngOnInit(): void {

  }

}

calculator.component.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <div class="card">
        <div class="card-header">CALCULATOR</div>
        <div class="card-body">
            <div class="form-group value">
                <div class="form-group row">
                    <label class="col-md-2 col-form-label">Value 1:</label>
                    <div class="col-md-10 input-1">
                        <input [(ngModel)]='number1' class="form-control inp" type="number" name="num1">
                    </div>
                </div>
                <div class="form-group row">
                    <label class="col-md-2 col-form-label">Value 2:</label>
                    <div class="col-md-10 input-2">
                        <input [(ngModel)]='number2' class="form-control inp" type="number" name="num2">
                    </div>
                </div>
            </div>
            <div class="buttons">
                <br>
                <button class="butt" (click)='sum()'> + </button>&nbsp;&nbsp;&nbsp;
                <button class="butt" (click)='diff()'> - </button>&nbsp;&nbsp;&nbsp;
                <button class="butt" (click)='mult()'> x </button>&nbsp;&nbsp;&nbsp;
                <button class="butt" (click)='divi()'> / </button>
                <br><br><br>
            </div>
            {{result}}
        </div>
    </div>
</body>

</html>

app-routing.module.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { CalculatorComponent } from './calculator/calculator.component';
import { ResultComponent } from './result/result.component';


const appRoutes: Routes = [
{ path: 'calculator', component: CalculatorComponent },
{ path: 'result', component: ResultComponent }
];

@NgModule({
  imports: [RouterModule.forRoot(appRoutes,
    { enableTracing: true } // <-- debugging purposes only
  )],
  exports: [RouterModule]
})
export class AppRoutingModule { }

app.component.html

<h1>Angular Router</h1>
<nav>
    <a routerLink="/calculator" routerLinkActive="active">Calculator</a><br>
    <a routerLink="/result" routerLinkActive="active">Result</a>
</nav>
<router-outlet></router-outlet>

data.service.ts

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class DataService {

  constructor() { }
}


Solution

  • There are multiple ways to do this,

    1. The simplest way can be to use state while navigating to result route from calculator route.
    this.router.navigate(['result'], { state: { result } });
    

    This will put your result in window.history.state object, which then you can access from result component.

    ngOnInit() {
        this.resultValue = window.history.state.result;
    }
    

    Demo


    2. You can also store the result in shared service and then access that variable from result component. Inject the service wherever required and store the retrieve data from it.

    @Injectable()
    export class SharedServiceService {
      storeValue: number = 0;
      constructor() { }
    }