0
0
Angularframework~30 mins

Why design patterns matter in Angular - See It in Action

Choose your learning style9 modes available
Why Design Patterns Matter in Angular
📖 Scenario: You are building a simple Angular app that manages a list of tasks. To keep your code clean and easy to maintain, you will use a design pattern called the Singleton pattern to manage the task data in one place.
🎯 Goal: Build an Angular standalone service using the Singleton pattern to store and manage tasks, then use it in a component to display the tasks.
📋 What You'll Learn
Create a standalone Angular service called TaskService that holds a list of tasks.
Add a configuration variable maxTasks to limit the number of tasks.
Implement a method addTask in TaskService that adds a task only if the list has fewer than maxTasks.
Create a standalone Angular component called TaskListComponent that uses TaskService to display the tasks.
💡 Why This Matters
🌍 Real World
Managing shared data like tasks, user info, or settings in one place is common in real apps. Singleton services help keep data consistent and easy to update.
💼 Career
Understanding design patterns and Angular services is essential for building scalable, maintainable web applications in professional development.
Progress0 / 4 steps
1
Create the TaskService with initial tasks
Create a standalone Angular service called TaskService with a public property tasks initialized to an array containing exactly these strings: 'Buy groceries', 'Walk the dog', and 'Read a book'.
Angular
Need a hint?

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

2
Add a maxTasks configuration variable
Inside the TaskService, add a public property called maxTasks and set it to the number 5.
Angular
Need a hint?

Just add maxTasks = 5; inside the class.

3
Add addTask method with maxTasks check
In TaskService, add a public method called addTask that takes a string parameter task. The method should add task to the tasks array only if the current number of tasks is less than maxTasks.
Angular
Need a hint?

Use this.tasks.length to check the current number of tasks.

4
Create TaskListComponent to display tasks
Create a standalone Angular component called TaskListComponent. Inject TaskService in its constructor. In the component template, use *ngFor to display each task from taskService.tasks inside a <li> element within a <ul>.
Angular
Need a hint?

Use *ngFor="let task of taskService.tasks" inside the template to loop over tasks.