I am wondering how to make add button update in total with the price
<table class=" container table table-striped table-hover ">
<thead>
<tr>
<th scope="col">Activity</th>
<th scope="col">Name</th>
<th scope="col">1 hour</th>
<th scope="col">30 min.</th>
<th scope="col">Summary</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let item of bookAdd">
<td>
img
</td>
<td> {{item.name}} </td>
<td *ngFor="let pointer of item.price; index as i" >{{pointer}}
<button type="button" class="btn btn-dark btn-sm">Add</button>
</td>
</tr>
<tr>
<th scope="row">3</th>
<td colspan="3"></td>
<td>
<p>
total
</p>
</td>
</tr>
</tbody>
export class BookingComponent implements OnInit {
bookAdd: Booking[] = [];
constructor(private booking: BookingService, private CartService: CartService) { }
ngOnInit(): void {
this.booking.getBooking().subscribe((data) => {
this.bookAdd = data;
console.log(this.bookAdd);
});
}
}
Solution 1
For getting the total price for added booking,
(click)
event to the button to call addTotalPrice
method by passing the price (pointer
).<button
type="button"
class="btn btn-dark btn-sm"
(click)="addTotalPrice(pointer)"
>
Add
</button>
total
variable. Add addTotalPrice
with one argument: price
and sum with total
.export class AppComponent {
total = 0;
...
addTotalPrice(price: number) {
this.total += price;
}
}
total
in HTML.<td>
<p>
{{ total }}
</p>
</td>
Solution 2
Adding feature that you want to keep track for each item how many 1 hour, 30 mins are clicked.
(click)
event to the button to call addBookings
method by passing the name
, price index (i
) and price (pointer
).<button
type="button"
class="btn btn-dark btn-sm"
(click)="addBookings(item.name, i, pointer)"
>
Add
</button>
2.1. Create booksSelected
array.
2.2. Transform an array for booksSelected
based on bookAdd
. For each item add priceSelected
(key-value pair with key is the price index (from price
array) and value is selected time) and subTotal
properties.
2.3. Implement addBookings
method. Aim to search the item from the bookAdd
by name, then update the value of the filtered item for priceSelected
and subTotal
properties.
2.4. Implement bookingsTotal
getter by summing the subTotal
for each item in bookingsSelected
.
export class AppComponent {
booksSelected: any[] = [];
...
ngOnInit() {
this.bookingService.getBooking().subscribe((data) => {
this.bookAdd = data;
console.log(this.bookAdd);
this.booksSelected = data.map((x: any) => {
x.priceSelected = x.price.reduce((acc, cur) => {
let keyIndex = Object.keys(acc).length;
acc[keyIndex] = 0;
return acc;
}, {});
x.subTotal = 0;
return x;
});
});
}
addBookings(name: string, i: number, price: number) {
let index = this.booksSelected.findIndex((x) => x.name == name);
this.booksSelected[i].priceSelected[i] += 1;
this.booksSelected[i].subTotal += price;
}
get bookingsTotal() {
return this.booksSelected.reduce((prev, cur) => {
prev += cur.subTotal;
return prev;
}, 0);
}
}
bookingsTotal
in HTML.<td>
<p>
{{ bookingsTotal }}
</p>
</td>