DEV Community

Cover image for Getting Started with Angular: Building Your First Todo List App
Ivan Bowen
Ivan Bowen

Posted on

Getting Started with Angular: Building Your First Todo List App

Introduction

Welcome to the world of Angular! If you're new to web development or looking to dive into modern frontend frameworks, you've come to the right place. In this beginner-friendly guide, we'll walk you through the process of building your first Angular application: a simple Todo List App.

Angular is a popular JavaScript framework maintained by Google, designed to simplify the development of dynamic web applications. With Angular, you can create interactive user interfaces, handle data seamlessly, and build robust single-page applications (SPAs) with ease.

Prerequisites

Before diving into Angular development and building your first Todo List App, it's essential to ensure that you have a some understanding of several key technologies and concepts. Here are the prerequisites you'll need to get started:

  1. JavaScript(JS) - Scrimba - learn JavaScript
  2. HTML (Hypertext Markup Language) and CSS - Link to a learning resource
  3. TypeScript - Typescript for Beginners

Steps to follow

Building a Todo List App with Angular involves several key steps. Here's a simplified outline of the process:

  1. Set Up Your Development Environment
  2. Create a New Angular Project
  3. Generate Components
  4. Define Todo List Structure and Logic
  5. Style Your Todo List
  6. Test Your Todo List App

Step 1: Setting up your Development Environment

To set up Angular, ensure Node.js is installed:

Install Node.js:

  • Download and install Node.js from the official website. Check installation using node -v and npm -v in the terminal.
  • Install Angular CLI: Globally install Angular CLI with npm install -g @angular/cli.
  • Verify Installation: Confirm Angular CLI installation with ng version.

Step 2: Create a New Angular Project

To create a new Angular project for your todo list:

  • Open your terminal or command prompt.

  • Navigate to the directory where you want to create your Angular project.

  • Run the following command:
    ng new todo-list-app

Angular CLI will prompt you to choose various project settings. You can select options like routing, stylesheet format, and more based on your preferences. Press Enter to confirm your selections.

Once the project is created, navigate into the project directory:

cd todo-list-app

Your new Angular project named todo-list-app is now set up and ready for development! You can start building your todo list within this project structure.

To open your project in the browser run:

ng serve --open

Step 3: Generate todo-list Component

Components are the building blocks of Angular applications. They are self-contained, reusable pieces of UI that consist of an HTML template, TypeScript class (component logic), and CSS styles. In Angular, the UI of your application is composed of a tree of components, where each component represents a part of the user interface.

  1. Clear Data in app.component.html and app.component.css
  • Open the app.component.html file and remove any default content within the <div> element.
  • Open the app.component.css file and remove any default styles.
  1. Generate the todo-list Component:
  • Open your terminal or command prompt.
  • Navigate to the root directory of your Angular project if you're not already there.
  • Run the following command to generate the todo-listcomponent

ng generate component todo-list

3.After generating the todo-list component, you can start building the UI and logic for your todo list within the component files. The generated component files will provide a starting point for you to define the structure, behavior, and styling of your todo list component.

Step 4: Defining your Todo List Structure and Logic

sessionStorage and localStorage are two web storage APIs provided by modern web browsers to store key-value pairs locally in the user's browser. They are used to persist data across page reloads and browser sessions.

  1. sessionStorage: The sessionStorage object stores data for only one session. Data stored in sessionStorage is available only for the duration of the page session. When the browser tab or window is closed, the data is cleared.

  2. localStorage: The localStorage object stores data with no expiration date. Data stored in localStorage persists even after the browser is closed and reopened. It remains stored until explicitly removed or cleared by the user or the application.

<-- todo-list.component.html -->
<div>
    <input type="text" #todoText placeholder="Add Todo">
    <button (click)="addTask(todoText.value)">Add</button>
</div>

<ul>
    <li *ngFor="let todoItem of todoList">
        <input
            type="checkbox"
            [(checked)]="todoItem.completed"
            (change)="toggleCompleted(todoItem.id)"
        />
        <span [class.completed]="todoItem.completed">{{ todoItem.task }}</span>
        <button (click)="deleteTask(todoItem.id)">Delete</button>
    </li>
</ul>
Enter fullscreen mode Exit fullscreen mode
  • The HTML code consists of an input field for adding a new todo item and a button to add it.
  • Below that, there is an unordered list (ul) that displays the todo items using Angular's *ngFor directive, which iterates over the todoList array.
  • Each todo item is displayed as a list item (li) with a checkbox, the task description, and a delete button.
  • Event bindings ((click), (change)) are used to handle user interactions such as adding tasks, toggling task completion status, and deleting tasks.
export class TodoListComponent implements OnInit {
    todoList: TodoItem[] = [];
    newTask: string = '';
    @ViewChild('todoText') todoInputRef: ElementRef<HTMLInputElement> = null!;

    constructor() { }

    ngOnInit(): void {
        const storedTodoList = localStorage.getItem('todoList');
        if (storedTodoList) {
            this.todoList = JSON.parse(storedTodoList);
        }
    }

    addTask(text: string): void {
        if (text.trim() !== '') {
            const newTodoItem: TodoItem = {
                id: Date.now(),
                task: text.trim(),
                completed: false
            };
            this.todoList.push(newTodoItem);
            this.todoInputRef.nativeElement.value = '';
            this.saveTodoList();
        }
    }

    deleteTask(id: number): void {
        this.todoList = this.todoList.filter(item => item.id !== id);
        this.saveTodoList();
    }

    toggleCompleted(id: number): void {
        const todoItem = this.todoList.find(item => item.id === id);
        if (todoItem) {
            todoItem.completed = !todoItem.completed;
            this.saveTodoList();
        }
    }

    saveTodoList(): void {
        localStorage.setItem('todoList', JSON.stringify(this.todoList));
    }
}
Enter fullscreen mode Exit fullscreen mode
  • This TypeScript code defines the TodoListComponent class, which implements Angular's OnInit interface Want to learn more about classes and objects in Javascript?.
  • The class includes properties such as todoList (an array of todo items) and newTask (a string to store new task input).
  • In the ngOnInit() method, it retrieves the todo list from localStorage and initializes the todoList array.
  • Methods like addTask, deleteTask, and toggleCompleted are defined to handle todo list operations such as adding, deleting, and toggling completion status of tasks.
  • The saveTodoList() method is responsible for saving the updated todo list to localStorage after any modifications.

Step 5: Styling

Feel free to customize these styles according to your design preferences and requirements by modifying the todo-list.component.css and giving classes in your html. With CSS, you have the flexibility to create a visually appealing and engaging todo list app that meets the needs of your users.

Conclusion

In conclusion, building a Todo List App with Angular is not just about creating a functional application; it's also an opportunity to delve into the world of modern web development and explore the power of Angular as a frontend framework. Throughout this journey, you've learned the essentials of Angular, from setting up your development environment to generating components, handling data, and styling your application.
With dedication, practice, and a curious mindset, you'll continue to grow as a web developer and unlock new opportunities in the exciting world of Angular development. Keep coding, keep learning, and enjoy the journey ahead!

Top comments (0)