Learn How to Create Your First Angular App in 20 Minutes

Angular is a powerful and popular JavaScript framework for building interactive single-page applications (SPAs). Developed and maintained by Google, Angular provides a component-based architecture, a rich ecosystem of developer tools, and a wide array of features right out of the box.

While Angular has a reputation for a steeper learning curve compared to some other frontend frameworks, getting started with a basic application is quite approachable. In this guide, we‘ll walk through building a simple to-do list app from scratch to introduce you to the core concepts and development process of Angular.

Why Choose Angular?

Angular is one of the most widely adopted frontend frameworks, powering many large-scale web applications across industries. According to the 2020 StackOverflow Developer Survey, Angular ranks as the third most popular web framework among professional developers, behind only jQuery and React.

Some of the key benefits and features of Angular include:

  • Component-based architecture: Angular apps are built as a tree of independent components, each encapsulating its own template, styles, and behavior. This modular structure makes code more reusable, maintainable, and easier to unit test.

  • TypeScript language: Angular is built with TypeScript, a typed superset of JavaScript. TypeScript adds optional static typing, classes, and other features that help catch errors early, provide better tooling, and improve code maintainability.

  • Comprehensive CLI: The Angular CLI is a command-line tool that automates many development tasks, from scaffolding new components to building and deploying apps for production. The CLI adheres to Angular‘s best practices and naming conventions.

  • Dependency injection: Angular has a built-in dependency injection system that manages the instantiation and lifecycle of service dependencies for components. This promotes loose coupling and makes it easier to test components in isolation.

  • Reactive programming with RxJS: Angular leverages RxJS, a library for composing asynchronous code using observable sequences. RxJS is used extensively in Angular for event handling, HTTP requests, and managing state.

Angular‘s History and Versions

Angular has undergone significant changes since its initial release. The original AngularJS (now referred to as Angular 1.x) was released by Google in 2010. While AngularJS was widely adopted, the Angular team decided to do a complete rewrite for the next major version to address architectural limitations and keep up with evolving web standards.

Angular 2 was released in 2016, with a component-based architecture, a new templating syntax, and a switch to TypeScript as the primary language. This new version was not backwards compatible with AngularJS, requiring a full migration to upgrade existing apps.

Since Angular 2, the framework has followed a predictable release schedule with semantic versioning. The current major version is Angular 12, released in May 2021. Each major version is expected to be backwards compatible with the prior major release, making upgrades much easier than the AngularJS to Angular 2 transition.

Setting Up Your Angular Development Environment

Before we dive into building an Angular app, let‘s make sure you have the necessary tools installed on your machine.

Prerequisites

  • Node.js and npm: Angular requires a current, active LTS or maintenance LTS version of Node.js, along with the npm package manager. You can download the installer from the official Node.js website.

    To check your versions, run the following commands in a terminal:

    node -v
    npm -v 
  • Angular CLI: The Angular CLI is the recommended tool for initializing, developing, and maintaining Angular apps. Install it globally with npm:

    npm install -g @angular/cli

    Verify your installation with:

    ng version

Creating a New Angular Project

With the Angular CLI installed, we can now generate a new Angular project. Open a terminal, navigate to the directory where you want to create your project, and run:

ng new todo-app

The CLI will prompt you for some configuration options. For this tutorial, you can accept the defaults or configure as desired. The CLI will then create the project files and install the necessary npm packages, which may take a few minutes.

Once the installation is complete, navigate into the project directory:

cd todo-app

To preview the default app in the browser, start the development server with:

ng serve --open

This command builds the app, starts a local web server, and opens the app URL (http://localhost:4200) in your default browser. The app will automatically reload if you change any of the source files.

Creating Your First Component

In Angular, components are the building blocks of the user interface. Let‘s create a component to represent an individual to-do item.

Using the Angular CLI, generate a new component named todo-item with the following command:

ng generate component todo-item

This command generates the following files in the src/app/todo-item directory:

  • todo-item.component.html: The component template
  • todo-item.component.ts: The component class
  • todo-item.component.css: The component styles
  • todo-item.component.spec.ts: The unit test file for the component

Open the todo-item.component.ts file and replace its contents with:

import { Component, Input } from ‘@angular/core‘;

@Component({
  selector: ‘app-todo-item‘,
  templateUrl: ‘./todo-item.component.html‘,
  styleUrls: [‘./todo-item.component.css‘]
})
export class TodoItemComponent {
  @Input() todo: string;
}

This defines a TodoItemComponent class with a single todo property, decorated with @Input(). The @Input() decorator indicates that the value of todo will be passed in from a parent component.

Next, update the todo-item.component.html template to display the todo property:

<div>{{ todo }}</div>

Creating the To-Do List Component

Now let‘s create a parent component to manage the list of to-do items. Generate a new component named todo-list:

ng generate component todo-list

Open the todo-list.component.ts file and replace its contents with:

import { Component } from ‘@angular/core‘;

@Component({
  selector: ‘app-todo-list‘,
  templateUrl: ‘./todo-list.component.html‘,
  styleUrls: [‘./todo-list.component.css‘]
})
export class TodoListComponent {
  todos: string[] = [
    ‘Buy groceries‘,
    ‘Do laundry‘,
    ‘Walk the dog‘
  ];
}

This defines a TodoListComponent class with a todos property initialized with an array of sample to-do items.

Update the todo-list.component.html template to loop through the todos array and render a TodoItemComponent for each item:

<h2>To-Do List</h2>
<app-todo-item *ngFor="let todo of todos" [todo]="todo"></app-todo-item>

The *ngFor directive is used to iterate over the todos array. For each item, an <app-todo-item> element is rendered, with its todo property bound to the current todo value.

To use the TodoListComponent in your app, open the app.component.html file and replace its contents with:


<app-todo-list></app-todo-list>

Save all files and run ng serve if it‘s not already running. Navigate to http://localhost:4200 in your browser. You should see the to-do list displayed with the sample items.

Adding New To-Do Items

Let‘s add the ability for users to create new to-do items. Update the todo-list.component.html template to include a form:

<h2>To-Do List</h2>
<form (ngSubmit)="addTodo(newTodo); newTodo=‘‘">
  <input name="newTodo" [(ngModel)]="newTodo">
  <button type="submit">Add</button>
</form>
<app-todo-item *ngFor="let todo of todos" [todo]="todo"></app-todo-item>

This template uses an Angular template-driven form with the ngSubmit event binding to call an addTodo() method when the form is submitted. The [(ngModel)] syntax creates a two-way data binding between the input value and the newTodo property.

In the todo-list.component.ts file, add the newTodo property and addTodo() method:

export class TodoListComponent {
  todos: string[] = [
    ‘Buy groceries‘,
    ‘Do laundry‘, 
    ‘Walk the dog‘
  ];

  newTodo = ‘‘;

  addTodo(todo: string) {
    this.todos.push(todo);
  }
}

The addTodo() method simply appends the todo parameter to the todos array.

To enable the ngModel directive used in the form, open the app.module.ts file and add FormsModule to the imports array:

import { FormsModule } from ‘@angular/forms‘;

@NgModule({
  // ...
  imports: [
    // ...
    FormsModule
  ],
  // ...
})

Now if you enter text in the input field and click the "Add" button, the new item will be added to the to-do list.

Marking Items as Complete

To allow users to mark items as complete, we‘ll add a checkbox next to each item. First, update the TodoItemComponent to include a completed property and an onChange event emitter:

import { Component, EventEmitter, Input, Output } from ‘@angular/core‘;

@Component({
  selector: ‘app-todo-item‘,
  templateUrl: ‘./todo-item.component.html‘,
  styleUrls: [‘./todo-item.component.css‘]
})
export class TodoItemComponent {
  @Input() todo: string;
  @Input() completed: boolean;
  @Output() completedChange = new EventEmitter<boolean>();

  onCompletedChange() {
    this.completedChange.emit(this.completed);
  }
}

The @Output() completedChange is an EventEmitter that will emit the new completed value to the parent component when it changes.

Update the todo-item.component.html template to include a checkbox bound to the completed property:

<div>
  <input type="checkbox" [(ngModel)]="completed" (change)="onCompletedChange()">
  <span [ngClass]="{‘completed‘: completed}">{{ todo }}</span>
</div>

The [(ngModel)] binds the checkbox state to the completed property. The (change) event binding triggers the onCompletedChange() method when the checkbox is toggled. The [ngClass] binding conditionally applies a .completed CSS class to the <span> element when completed is true.

Add the following styles to todo-item.component.css:

.completed {
  text-decoration: line-through;
}

In the TodoListComponent, update the todos property to be an array of objects with title and completed properties:

todos: any[] = [
  { title: ‘Buy groceries‘, completed: false },
  { title: ‘Do laundry‘, completed: true },
  { title: ‘Walk the dog‘, completed: false }
];

Update the addTodo() method to append a new object to the array:

addTodo(title: string) {
  this.todos.push({
    title,
    completed: false
  });
}

And update the todo-list.component.html template to pass the completed property and handle the completedChange event:

<app-todo-item *ngFor="let todo of todos"
               [todo]="todo.title"
               [completed]="todo.completed"
               (completedChange)="todo.completed = $event"></app-todo-item>

The $event variable holds the value emitted by the completedChange event, which is assigned to todo.completed.

With these changes, you can now toggle the completed state of each to-do item, and completed items will appear with a strike-through style.

Summary and Next Steps

Congratulations! You‘ve built a basic but functional Angular to-do list application. In the process, you learned how to:

  • Set up an Angular development environment with the Angular CLI
  • Create and use components
  • Pass data between parent and child components with input and output bindings
  • Use template-driven forms and two-way data binding
  • Conditionally apply styles with the ngClass directive

This is just a starting point. Some potential enhancements you could make to the app include:

  • Persisting the to-do items to local storage or a backend service
  • Adding the ability to edit and delete items
  • Categorizing items with tags or lists
  • Improving the UI with styles, animations, or a component library like Angular Material

To learn more about Angular, consult the official documentation, which includes a getting started guide, tutorials, and API reference. The Angular community is also very active, with numerous blogs, podcasts, courses, and conferences to help you connect with other developers and stay up to date with the latest features and best practices.

Some additional resources to explore:

With its powerful features and extensive ecosystem, Angular is a strong choice for building complex, high-performance web applications. Its adoption by many large companies and active development by Google ensure its continued relevance and evolution in the rapidly changing frontend landscape. While it may take some time and effort to fully master Angular, the skills you learn will be valuable and transferable across a wide range of projects and teams.

Similar Posts