I'm new to Typescript, i'm working on creating Cost calculator application. I have 8 question as separate components and totalCost component. Each question have 3 different options to select. upon selecting option I want Total cost to add up as user progress in questions. Once user answer final question I was summary to present him with Total Cost.
I did research and came across different answers but non of them seems to be working for me. Most of the answers given are in JS.
I tried using rxjs/BehaviorSubject
library but got error. Here is my code.
totalCost.component.ts
import { Component, Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/internal/BehaviorSubject';
@Component({
selector: 'totalcost',
template: `<div>
<p>Total: {{totalCost}}
</div>`
})
@Injectable({
providedIn: 'root'
})
export class TotalCost {
private totalCost = new BehaviorSubject<number>(0);
currentCost = this.totalCost.asObservable();
constructor(){
}
addCost(add: number){
this.totalCost.next(add);
console.log('addCost');
return this.totalCost;
}
}
Here is the first question component:
import { Component, OnInit, Injectable } from '@angular/core';
import { TotalCost } from '../totalCost/totalCost.component';
@Injectable({
providedIn: 'root'
})
@Component({
selector: 'first',
templateUrl: './first.component.html',
styleUrls: ['./first.component.scss']
})
export class First {
totalCost: number;
constructor(private cost: TotalCost){
}
ngOnIt(){
this.cost.currentCost.subscribe(totalCost => this.totalCost = totalCost )
}
addToCost(value: number){
this.cost.addCost(value);
console.log('addToCost()');
}
}
here is HTML for First Question:
<div class="container-fluid text-center">
<div>
<h3>Choose The Type Of Website</h3>
<input type="range" value="1000" id="budget">
<p>
<span>
<a [routerLink]="'/second'" (click)="addToCost(1000)"><img src="" alt="static"></a>
</span>
<span>
<a [routerLink]="'/second'" ><img src="" alt="Dynamic"></a>
</span>
<span>
<a [routerLink]="'/second'" ><img src="" alt="E-Commerce"></a>
</span>
</p>
</div>
</div>
When user select one of the option I want Total cost to add up until user reach last question.
This is what my application look like