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

Files touched

--- 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',
+    });
+  }
 }
 

Review this PR

Angular practice