DEV Community

Eboreime Rhoda
Eboreime Rhoda

Posted on

Getting Started with Angular: A Step-by-Step Guide

Hello there, aspiring Angular developers! Whether you're just stepping into the world of web development or looking to expand your skill set, you've come to the right place. Welcome to the Angular Mastery Series: From Fundamentals to Real-World Projects, where we're embarking on an exciting journey through the ins and outs of one of the most potent front-end frameworks – Angular. This is the first article in this series.

Angular is more than just a framework; it's a way to create dynamic and sophisticated web applications. In this series, I'll take you from the very basics of Angular to building real-world projects that showcase your newfound skills. My goal is to help you become a confident and skilled Angular developer capable of creating modern, interactive, and efficient applications.

Let's get started!

Let's get started!


Tutorial Outline


Introduction

As I have explained at the beginning of this post, angular is a popular framework used for building web applications. It is primarily written in Typescript, open source and provides single page transitions for web apps.

Why you should consider using Angular For your next project

  • Angular allows you to build scalable web apps. So if you're thinking of a framework that has the capacity to handle heavier workloads as time goes on, Angular is a goto.

  • Angular basically provides most of the libraries that you'll need to build your app. This reduces the use of third party libraries. These libraries have features that covers routing, client-server communication, styling, animations and so on.

  • Lastly for this article, angular comes with development tools you'll need as you progress on your web app development stages. From the development phase to the testing phase.

Prerequsites

To successfully follow along, I recommend you have a foundational knowledge of:

  • HTML
  • JavaScript
  • TypeScript

Recommended softwares are:

  • An IDE (VS code, Sublime text etc).
  • Node.js
  • NPM

Setting Up the Development Environment

You can code your project in an online environnment like StackBlitz or CodeSandBox. For this tutorial and subsequent ones, I will be using my local environment setup. You can follow along either way you prefer.

Configuring your local development environment

After installing Node.js and NPM (Node Package Manager), the next thing is to set up your Angular workspace.

Install the CLI (Command Line Interface)
npm install -g @angular/cli
This would install the Angular CLI globally.

Creating a new angular project

For this tutorial, we're going to be building a todo app. Sounds like a good place to start! We'll tackle advanced projects as we progress in this series.

Open your code editor and then open the terminal. Create a new folder for angular projects in your preferred location with the mkdir command.

mkdir Angular-projects
Enter fullscreen mode Exit fullscreen mode

This would create a new folder. Still in your terminal, cd into the new folder you created and type the command

ng new TodoApp
Enter fullscreen mode Exit fullscreen mode

This would start creating our angular application.

ng is the command keyword for performing Angular operations. It is used with other keywords. We would use it a lot in our project. To see the list of all available commands, in your terminal, run ng --help.

You will be prompted with some questions.

Would you like to add Angular routing? No
For our basic todo app, we would not be using angular routing.

Which stylesheet format would you like to use? CSS

Click enter to select an option. Down arrow and up arrow keys for movement. For this project, I'll be using CSS but you can select your preferred option.

After these prompts, Angular would start creating our todo app project. If this was successful, you should see a message that says "packages successfully installed".

Open the folder you just created in a new window. You should see the basic folder structure of an angular project.

Angular folder structure

Next, we're going to start our application so that it runs in the browser.

Open a new terminal and run ng serve or npm start. Either of them would run your appication. Go to http://localhost:4200/ to see it.

We have successfully created our Angular project!

Building the UI: Creating Components

Its time to create the components for our app. Components are like building blocks for an application. Instead of having a central component, the app implementation is split into units. This is one advantage of using Angular. If you've used React, then you should be familiar with the concept of components.

Our Todo application will have three components, and the default app component making it four. The first component would be the header. The second is the todo list component where the app logic would be and the last is a footer component. Below is a wireframe showing the way the components are divided.

Todo App Components

cd into your src directory and then, into your app directory. Create a components folder mkdir components.

Next, cd into the components folder you just created.

To create the first component run the command

ng generate component header

This would generate the Header component.

Similarly, run

ng generate component todolist

ng generate component footer
Enter fullscreen mode Exit fullscreen mode

ng generate component can be shortened to ng g c.

If you check your components folder, you should see the new components.

You may have noticed that each of the components have four files.

  • file.component.css - This is where your CSS code will be.
  • file.component.html - This is where the content that would be displayed on the webpage would be.
  • file.component.spec.ts - This is the test file for this component. You don't need to edit it.
  • file.component.ts - This is the typescript file where the logic of the component would be.

Your CSS file should be blank. Your HTML file should show a p tag and your .ts file should show be like this:

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

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.css']
})
export class HeaderComponent {

}

Enter fullscreen mode Exit fullscreen mode

The first line just imports the Component decorator from the @angular/core module. It is used to define Angular components. You'll see it in every component.

Next, we see the component definition. Three important terms are inside the component declaration.

selector - This is the HTML selector for the component.
templateUrl - This holds the path to the HTML file for the component.
styleUrls - This holds the paths to the CSS files that would be used in the component.

Below this is the class declaration for this component. Each component has a class declaration that defines properties and methods for the application logic.

We're going to start by clearing out the default files.

Go to your app.component.html file. Highlight everything and clear it out. Then add the following HTML selectors for the components we created.

<!--Header component-->
<app-header></app-header>

<!--Todolist component-->
<app-todolist></app-todolist>

<!--Footer component-->
<app-footer></app-footer>
Enter fullscreen mode Exit fullscreen mode

Quickly, we'll add a simple header and footer so that we can focus on building the todo app.

In your header.component.html add the following (you can also customize it):

<div>
    <h1 class="header">My TodoApp</h1>
</div>
Enter fullscreen mode Exit fullscreen mode

In your footer add a "Built by [name]" (you can also customize it).

<div>
    <p>Built by Rhoda</p>
</div>
Enter fullscreen mode Exit fullscreen mode

Now, it's time to start the main app.

Data Binding: Connecting UI and Data

Data binding has to do with connecting your data with your User Interface (UI). It's like the thread that weaves together the fabric of your web application, making it both interactive and dynamic. Angular has two major categories of data binding.

There is the one-way data binding where just as the name implies, the data flows in one direction. That is, the data can be connected to the UI and the UI would be updated with the components data. However, the UI cannot update the component's data. You should use this if you only need to display data from the component in the UI but do not need to capture user input or changes in the UI back into the component.

The other is the two-way data binding which is an opposite and extension of the one-way data binding. It allows data to flow in both directions. That is, from the data component to the UI and from the UI to the data component.

There are many examples of these data bindings and we would encounter them as we begin our app.

Here's the HTML skeleton of the todo list

<!--todo component-->
<div class="todo-container">
  <div class="todo-input">
    <input placeholder="Add a new task" />
    <button>Add</button>
  </div>
  <ul class="task-list">
    <li>todo</li>
    <button>Delete</button>
  </ul>
</div>
Enter fullscreen mode Exit fullscreen mode

For our data component, first, we'll need an array where we can push the new todo items into. We'll also need a variable to store the new items to be added to the todo list. Then, we'll need an add and delete function that will handle the addition of items to our list and deletion of items.

//todo array
 todos: string[] = [];
//new todo item
  newTodo: string = '';

//function to add items to to do array
addTodo() {
    if (this.newTodo.trim() !== '') {
      this.todos.push(this.newTodo);
      this.newTodo = '';
    }
  }

 //function to delete items from to do array
  deleteTodo(todo: string) {
    const index = this.todos.indexOf(todo);
    if (index !== -1) {
      this.todos.splice(index, 1);
    }
  }
Enter fullscreen mode Exit fullscreen mode

Once we've set up our data component, its time to connect the variable, array and methods to our UI.

Updating the UI with angular two-way binding

A common two-way binding used is the ngModel. It is used in a form element to get data from an input and then send the data to the property that would store the input.

Thus, in our app:

<input [(ngModel)]="newTodo" placeholder="Add a new task" />
Enter fullscreen mode Exit fullscreen mode

Here's a breakdown of what is happening:
The square brackets [ ] denote property binding (binding from component to the template), and the parentheses ( ) denote event binding (binding from the template to the component).

This combination allows the input field and the component property (newTodo) which the input is bound to, to stay synchronized in both directions.

When you type a task in the input field, the newTodo property of the component is updated with the input's value, and if there is any change in the newTodo property, the input would also be updated.

Important note: the ngModel binding is exported from the FormsModule library. We will need to import it in our app.module.ts file and add it in the imports array:

//other imports
import { FormsModule } from '@angular/forms';

@NgModule({
imports: [FormsModule]
})
Enter fullscreen mode Exit fullscreen mode

Updating the UI with event binding

Similar to javaScript event handlers, event binding listen for and responds to a user actions such as keystrokes, mouse movements, clicks, and touches.

(click) is a popular event binding that listens for a click event on the element it is binded to. We have created two methods for our todo app. We want an item to be added when the add button is clicked. We also want an item to be deleted when the delete button is clicked. To achieve this, we would bind the methods to their respective HTML buttons so that they would listen for a user's click and be triggered.

<button (click)="addTodo()">Add</button>
<button (click)="deleteTodo(todo)">Delete</button>
Enter fullscreen mode Exit fullscreen mode

Observe that the delete button has the todo argument passed to it. It takes in the specific todo item to be deleted.

Updating the UI with angular directives

Directives in Angular are like special instructions you give to your HTML elements. They tell Angular what to do with those elements or how they should behave. They are one of the ways to update a UI and make a web application more interactive and dynamic.

Learn more about directives.

In our todo app, we will need to use an angular directive to pass our array of todo items to the UI. Angular has different types of directives, one of which is the built in angular directive. We would come across all of them as we progress in this article series.

Built-in directives controls the HTMl elements and manupulates the UI. A popular one is *ngFor which works like a normal loop statement. That is, it loops through a list of items and returns each item in the list.

We have a list that holds the todo items a user adds and we want to loop through it and then display each item. To do this, we would use the *ngFor directive.

Update the HTMl to use this directive:

<li *ngFor="let todo of todos">
      <!--code-->
</li>
Enter fullscreen mode Exit fullscreen mode

Here's a breakdown of what is happening:
let todo of todos - This sets up the loop. It says: "For each item in the todos array, temporarily assign each item to the variable todo." In other words, it iterates through the todos array and assigns each element to the variable todo for each iteration.

Updating the UI with interpolation

Interpolation is a way to update a UI with string data.

The todo items would be string values therefore, we would use it to pass the looped todo items to the web page for the users to see.

   <li *ngFor="let todo of todos">
      <!--code-->
      {{ todo }}
</li>
Enter fullscreen mode Exit fullscreen mode

Now, a user can see the todo items they have on the web page.

Having explained these bindings, here is the full html template code with the bindings I explained:

<!--todo list component-->
<div class="todo-container">
  <div class="todo-input">
    <input [(ngModel)]="newTodo" placeholder="Add a new task" />
    <button (click)="addTodo()">Add</button>
  </div>
  <ul class="task-list">
    <li *ngFor="let todo of todos">
      <!--code-->
      {{ todo }}
      <button (click)="deleteTodo(todo)">Delete</button>
    </li>
  </ul>
</div>
Enter fullscreen mode Exit fullscreen mode

Remember, I have provided the full component's code already.

Styling the Application: Adding Basic CSS

I have provided a basic css styling below for the app:

.todo-container {
  width: 100%;
}
.todo-container input {
  padding: 10px;
}
.todo-container button {
  border: 1px;
  border-radius: 100%;
}
Enter fullscreen mode Exit fullscreen mode

Running the Application

Start your server with npm start or ng serve.


Conclusion

In conclusion, the todo app we've developed represents a fundamental example of a dynamic and interactive web application built using Angular. Throughout the process of creating this app, we've covered several key concepts and techniques that are foundational to web development with Angular. I have linked some resources below for a flexible learning experience.

In upcoming articles in this series, Angular Mastery Series: From Fundamentals to Real-World Projects, we would delve deeper into:

  • Mastering Angular Components and Directives
  • Exploring Angular Routing and Navigation

And more!

Top comments (0)