0
0
Angularframework~30 mins

Singleton service behavior in Angular - Mini Project: Build & Apply

Choose your learning style9 modes available
Singleton Service Behavior in Angular
📖 Scenario: You are building a simple Angular app that tracks a user's favorite color. The app has two components that both show and update the favorite color. You want to use a singleton service so both components share the same color data.
🎯 Goal: Create an Angular singleton service to hold the favorite color. Then build two components that both read and update this color through the service, so changes in one component reflect in the other.
📋 What You'll Learn
Create a singleton service called FavoriteColorService with a color property initialized to 'blue'.
Create a component called ColorDisplayComponent that shows the current favorite color from the service.
Create a component called ColorChangerComponent that updates the favorite color in the service.
Ensure the service is provided in the root injector to maintain singleton behavior.
💡 Why This Matters
🌍 Real World
Singleton services are used in Angular apps to share data or logic across multiple components without duplicating state.
💼 Career
Understanding singleton services is essential for Angular developers to manage shared state and build maintainable apps.
Progress0 / 4 steps
1
Create the singleton service with initial color
Create an Angular service called FavoriteColorService with a public property color set to 'blue'. Use the @Injectable decorator with providedIn: 'root' to make it a singleton.
Angular
Need a hint?

Use @Injectable({ providedIn: 'root' }) to make the service singleton.

2
Create ColorDisplayComponent to show the color
Create a component called ColorDisplayComponent that injects FavoriteColorService in its constructor. Display the service's color property in the template using interpolation.
Angular
Need a hint?

Inject the service in the constructor and use {{ favoriteColorService.color }} in the template.

3
Create ColorChangerComponent to update the color
Create a component called ColorChangerComponent that injects FavoriteColorService in its constructor. Add an input box bound to a local variable newColor and a button. When the button is clicked, update the service's color property to newColor.
Angular
Need a hint?

Use two-way binding with [(ngModel)] for the input and update the service color on button click.

4
Add components to app template for testing
In the main app component template, add the selectors <app-color-display> and <app-color-changer> so both components appear on the page. This will let you see the shared color and change it.
Angular
Need a hint?

Use the component selectors as HTML tags in the app template.