0
0
Angularframework~30 mins

Actions and reducers pattern in Angular - Mini Project: Build & Apply

Choose your learning style9 modes available
Actions and reducers pattern
📖 Scenario: You are building a simple Angular app to manage a counter. The app uses the actions and reducers pattern to update the counter state.
🎯 Goal: Create an Angular standalone component that uses signals and the actions and reducers pattern to increase and decrease a counter value.
📋 What You'll Learn
Create an initial state object with a count property set to 0
Create an action type variable called INCREMENT with value 'increment'
Create a reducer function called counterReducer that takes state and action and returns updated state
Create a standalone Angular component called CounterComponent that uses signals and the reducer to update and display the count
💡 Why This Matters
🌍 Real World
Managing state in Angular apps using actions and reducers helps keep your app predictable and easier to maintain, especially as it grows.
💼 Career
Understanding actions and reducers is key for Angular developers working with state management libraries or building scalable apps with clear state flow.
Progress0 / 4 steps
1
Create the initial state object
Create a constant called initialState that is an object with a property count set to 0.
Angular
Need a hint?

Use const initialState = { count: 0 }; to create the initial state.

2
Create the action type variable
Create a constant called INCREMENT and set it to the string 'increment'.
Angular
Need a hint?

Use const INCREMENT = 'increment'; to define the action type.

3
Create the reducer function
Create a function called counterReducer that takes parameters state and action. Inside, use a switch statement on action.type. If it matches INCREMENT, return a new state object with count increased by 1. Otherwise, return the original state.
Angular
Need a hint?

Use a switch on action.type and return updated state for INCREMENT.

4
Create the Angular component using signals and reducer
Create a standalone Angular component called CounterComponent. Inside, create a signal called state initialized with initialState. Create a function called dispatch that takes an action and updates state by calling counterReducer with current state() and the action. In the template, display the current count using {{ state().count }} and add a button with a click event that calls dispatch with an action of type INCREMENT. Use semantic HTML and add an aria-label to the button for accessibility.
Angular
Need a hint?

Use Angular signals and update state with the reducer inside dispatch. Add a button with click event and aria-label.