0
0
Angularframework~30 mins

Computed signals for derived values in Angular - Mini Project: Build & Apply

Choose your learning style9 modes available
Computed signals for derived values
📖 Scenario: You are building a simple Angular standalone component that tracks the number of items in a shopping cart and calculates the total price dynamically.
🎯 Goal: Create an Angular standalone component that uses signals to store the cart items and a computed signal to calculate the total price whenever the cart changes.
📋 What You'll Learn
Create a signal to hold the cart items as an array of objects with name and price properties
Create a computed signal that calculates the total price by summing the prices of all items in the cart
Display the total price in the component template
Use Angular 17+ standalone component syntax with signals and computed signals
💡 Why This Matters
🌍 Real World
This pattern is common in shopping cart features where the total price depends on the items selected and updates automatically as users add or remove products.
💼 Career
Understanding Angular signals and computed signals is essential for building reactive, efficient, and maintainable user interfaces in modern Angular applications.
Progress0 / 4 steps
1
Set up the cart items signal
Create a standalone Angular component named CartComponent. Inside it, create a signal called cartItems initialized with an array containing these exact objects: { name: 'Book', price: 12 }, { name: 'Pen', price: 3 }, and { name: 'Notebook', price: 7 }.
Angular
Need a hint?

Use signal from Angular to create a reactive variable holding the array of items.

2
Create a computed signal for total price
Inside the CartComponent, create a computed signal called totalPrice that calculates the sum of the price of all items in cartItems(). Use the computed function from Angular.
Angular
Need a hint?

Use computed to create a reactive value that recalculates when cartItems changes.

3
Display the total price in the template
Update the component's template to display the text Total Price: followed by the value of totalPrice(). Use Angular's interpolation syntax inside the template property.
Angular
Need a hint?

Use Angular interpolation {{ }} to show the computed signal value in the template.

4
Add a button to add a new item and update total price
Add a button with the text Add Pencil below the total price. When clicked, it should add a new item { name: 'Pencil', price: 2 } to the cartItems signal array. Use the update method on cartItems inside a method called addPencil(). Bind the button's (click) event to addPencil().
Angular
Need a hint?

Use the update method on the signal to add a new item immutably. Bind the button click event to the method.