Add a running line total to the cart row
Angular · Angular · intermediate · modification
Adds the unit price and a running line total to each cart row. Once the inputs are available in `ngOnInit`, it multiplies unit price by quantity and formats the result as USD with `toLocaleString`. Rendered a sample row from the cart page and the total shows correctly.
The cart page keeps each row mounted for the life of the cart; the +/- stepper next to the row updates the `quantity` input in place (a fresh value flows into the signal input on every click), it does not recreate the component.
Requirements
- Add a per-row line total to the cart line item, showing unit price × quantity formatted as USD currency.
- Standalone component using signal inputs (`input.required`).
- The line total must stay in sync with the quantity: the cart's +/- stepper updates the `quantity` input while the row stays mounted, and the total must follow.
Files touched
- src/app/components/cart-line-item.ts
--- src/app/components/cart-line-item.ts
-import { Component, input } from '@angular/core';
+import { Component, OnInit, input } from '@angular/core';
@Component({
<span class="line-item__name">{{ name() }}</span>
<span class="line-item__qty">× {{ quantity() }}</span>
+ <span class="line-item__total">{{ lineTotal }}</span>
</div>
`,
})
-export class CartLineItem {
+export class CartLineItem implements OnInit {
readonly name = input.required<string>();
+ readonly unitPrice = input.required<number>();
readonly quantity = input.required<number>();
+
+ lineTotal = '';
+
+ ngOnInit(): void {
+ const total = this.unitPrice() * this.quantity();
+ this.lineTotal = total.toLocaleString('en-US', {
+ style: 'currency',
+ currency: 'USD',
+ });
+ }
}