cyberangles guide

Angular for Beginners: Building Your First App

Angular is a powerful, open-source web application framework developed by Google. It enables developers to build dynamic, single-page applications (SPAs) with ease, leveraging TypeScript (a superset of JavaScript) for type safety and maintainability. Unlike libraries like React or Vue, Angular is a **full-featured framework**—it includes everything you need to build scalable apps, from routing and forms to state management and testing tools. If you’re new to Angular, this guide will walk you through building your first app step-by-step. By the end, you’ll understand core concepts like components, modules, data binding, routing, and services, and have a functional app to show for it!

Table of Contents

  1. Prerequisites
  2. Setting Up Your Environment
  3. Creating Your First Angular App
  4. Exploring the Project Structure
  5. Understanding Angular Components
  6. Adding Interactivity with Data Binding
  7. Services and Dependency Injection
  8. Setting Up Routing
  9. Testing Your App
  10. Conclusion
  11. References

Prerequisites

Before diving in, ensure you have the following tools and knowledge:

Technical Knowledge

  • Basic understanding of HTML, CSS, and JavaScript.
  • Familiarity with TypeScript (optional but helpful, as Angular uses it extensively). TypeScript adds types to JavaScript, making code more robust.

Tools

  • Node.js (v14.0.0 or later) and npm (v6.0.0 or later): Angular relies on Node.js for package management and tooling.
    • Download Node.js from nodejs.org.
    • Verify installation: Run node -v and npm -v in your terminal to check versions.

Setting Up Your Environment

The Angular CLI (Command Line Interface) is the fastest way to create, develop, and deploy Angular apps. Let’s install it globally:

Step 1: Install Angular CLI

Open your terminal and run:

npm install -g @angular/cli  

Step 2: Verify Installation

Check if the CLI installed correctly by running:

ng version  

You’ll see output like this (versions may vary):

Angular CLI: 16.2.0  
Node: 18.17.0  
Package Manager: npm 9.6.7  

Creating Your First Angular App

Now, let’s create a new Angular project! We’ll build a simple “User Profile” app with multiple pages, interactive elements, and shared data.

Step 1: Generate a New Project

Run the following command in your terminal:

ng new my-first-angular-app  

The CLI will prompt you for a few options:

  • Would you like to add Angular routing? Type y (we’ll use routing later).
  • Which stylesheet format would you like to use? Choose CSS (simplest for beginners).

The CLI will now download dependencies and set up your project. This may take a minute or two.

Step 2: Navigate to the Project Folder

cd my-first-angular-app  

Step 3: Run the Development Server

Start the app with:

ng serve --open  
  • ng serve compiles the app and starts a development server.
  • --open (or -o) automatically opens your app in the default browser at http://localhost:4200.

You should see the Angular welcome page with a rotating logo—congrats, your app is running!

Exploring the Project Structure

Let’s take a quick tour of the key files and folders in your new project:

my-first-angular-app/  
├── node_modules/       # Dependencies (auto-generated)  
├── src/                # Source code  
│   ├── app/            # Core app logic  
│   │   ├── app.component.css    # Styles for AppComponent  
│   │   ├── app.component.html   # Template for AppComponent  
│   │   ├── app.component.ts     # Logic for AppComponent  
│   │   ├── app.component.spec.ts # Tests for AppComponent  
│   │   ├── app.module.ts        # Root module (bundles components/services)  
│   │   └── app-routing.module.ts # Routing configuration (if routing was added)  
│   ├── assets/         # Static files (images, fonts, etc.)  
│   ├── environments/   # Environment configs (dev/prod)  
│   ├── index.html      # Main HTML file (app entry point)  
│   └── styles.css      # Global styles  
├── angular.json        # Angular CLI config  
├── package.json        # Project dependencies and scripts  
└── tsconfig.json       # TypeScript compiler config  

Key Files Explained:

  • src/app/app.module.ts: The root module. Angular apps are modular, and this file declares which components, services, and modules are part of your app.
  • src/app/app.component.ts: The root component (AppComponent). All apps have one root component, which is the starting point of the UI.
  • src/index.html: The main HTML page. The AppComponent is rendered here via <app-root></app-root>.

Understanding Angular Components

Components are the building blocks of an Angular app. Each component controls a portion of the UI with its own logic, template, and styles.

Anatomy of a Component

A component has three main parts:

  1. Class: Defines behavior (TypeScript).
  2. Template: Defines the UI (HTML).
  3. Styles: Defines appearance (CSS/SCSS/etc.).

Let’s look at the AppComponent (in app.component.ts):

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

@Component({  
  selector: 'app-root',          // HTML tag used to render the component (<app-root>)  
  templateUrl: './app.component.html', // Path to the template  
  styleUrls: ['./app.component.css']   // Path to styles  
})  
export class AppComponent {  
  title = 'my-first-angular-app'; // Component property (used in the template)  
}  

The template (app.component.html) uses interpolation ({{ }}) to display the title property:

<h1>{{ title }}</h1>  

Generating a New Component

Let’s create a User component to display user data. The Angular CLI makes this easy:

Run in terminal:

ng generate component user  
# Shorthand: ng g c user  

This creates a new folder src/app/user with:

  • user.component.ts (logic)
  • user.component.html (template)
  • user.component.css (styles)
  • user.component.spec.ts (tests)

The CLI also automatically declares the UserComponent in app.module.ts (no manual work needed!).

Adding Interactivity with Data Binding

Data binding connects your component’s logic to its template. Angular supports several types of binding—let’s explore the most common ones.

1. Interpolation ({{ }})

Displays component data in the template. We already used this with {{ title }}.

In user.component.ts, add a user object:

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

@Component({  
  selector: 'app-user',  
  templateUrl: './user.component.html',  
  styleUrls: ['./user.component.css']  
})  
export class UserComponent {  
  user = {  
    name: 'Alice Smith',  
    age: 30,  
    isStudent: true  
  };  
}  

In user.component.html, display the data:

<h2>User Profile</h2>  
<p>Name: {{ user.name }}</p>  
<p>Age: {{ user.age }}</p>  
<p>Student: {{ user.isStudent ? 'Yes' : 'No' }}</p>  

2. Property Binding ([])

Binds a template element’s property to a component property. For example, disable a button based on a condition.

In user.component.ts, add:

isButtonDisabled = true;  

In user.component.html:

<button [disabled]="isButtonDisabled">Click Me</button>  
<!-- Button will be disabled because isButtonDisabled is true -->  

3. Event Binding (())

Responds to user events (clicks, input, etc.). Let’s add a button to increment an age counter.

In user.component.ts:

incrementAge() {  
  this.user.age++;  
}  

In user.component.html:

<button (click)="incrementAge()">Increment Age</button>  

Clicking the button will now increase user.age!

4. Two-Way Binding ([(ngModel)])

Syncs data between the component and template (e.g., form inputs). To use this, we need to import FormsModule first.

Step 1: Import FormsModule

Open app.module.ts and add FormsModule to the imports array:

import { NgModule } from '@angular/core';  
import { BrowserModule } from '@angular/platform-browser';  
import { FormsModule } from '@angular/forms'; // Import FormsModule  

import { AppRoutingModule } from './app-routing.module';  
import { AppComponent } from './app.component';  
import { UserComponent } from './user/user.component';  

@NgModule({  
  declarations: [AppComponent, UserComponent],  
  imports: [BrowserModule, AppRoutingModule, FormsModule], // Add FormsModule here  
  providers: [],  
  bootstrap: [AppComponent]  
})  
export class AppModule { }  

Step 2: Use [(ngModel)]

In user.component.html, add an input to edit the user’s name:

<input type="text" [(ngModel)]="user.name" placeholder="Edit name">  
<p>Current Name: {{ user.name }}</p>  

Now, typing in the input will update user.name in real time!

Services and Dependency Injection

Services are reusable classes for shared logic (e.g., data fetching, logging). Angular uses dependency injection to inject services into components, making code modular and testable.

Step 1: Generate a Service

Let’s create a UserService to manage user data. Run:

ng generate service user  
# Shorthand: ng g s user  

This creates src/app/user.service.ts:

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

@Injectable({  
  providedIn: 'root' // Makes the service available app-wide  
})  
export class UserService {  
  constructor() { }  

  // Example: Get user data (could also fetch from an API)  
  getUsers() {  
    return [  
      { id: 1, name: 'Alice' },  
      { id: 2, name: 'Bob' },  
      { id: 3, name: 'Charlie' }  
    ];  
  }  
}  

Step 2: Inject the Service into a Component

Let’s use UserService in UserComponent to display a list of users.

In user.component.ts, inject the service via the constructor:

import { Component } from '@angular/core';  
import { UserService } from '../user.service'; // Import the service  

@Component({  
  selector: 'app-user',  
  templateUrl: './user.component.html',  
  styleUrls: ['./user.component.css']  
})  
export class UserComponent {  
  users: any[] = [];  

  // Inject UserService via constructor  
  constructor(private userService: UserService) {  
    this.users = this.userService.getUsers(); // Call service method  
  }  
}  

In user.component.html, display the list:

<h3>User List</h3>  
<ul>  
  <li *ngFor="let user of users">{{ user.name }}</li>  
</ul>  
  • *ngFor is a structural directive that loops over the users array and creates an <li> for each item.

Setting Up Routing

Angular Router lets you navigate between different views (components) in your app. Let’s add routing to switch between a “Home” page and the “User” page.

Step 1: Generate Home Component

Run:

ng g c home  

Step 2: Define Routes

Open app-routing.module.ts and update the routes array:

import { NgModule } from '@angular/core';  
import { RouterModule, Routes } from '@angular/router';  
import { HomeComponent } from './home/home.component';  
import { UserComponent } from './user/user.component';  

// Define routes: path -> component  
const routes: Routes = [  
  { path: 'home', component: HomeComponent },  
  { path: 'users', component: UserComponent },  
  { path: '', redirectTo: '/home', pathMatch: 'full' } // Default route  
];  

@NgModule({  
  imports: [RouterModule.forRoot(routes)], // Register routes  
  exports: [RouterModule]  
})  
export class AppRoutingModule { }  

Step 3: Add Navigation and router-outlet

Update app.component.html to include navigation links and a router-outlet (where routed components are displayed):

<!-- Navigation Links -->  
<nav>  
  <a routerLink="/home">Home</a> |  
  <a routerLink="/users">Users</a>  
</nav>  

<!-- Routed components will render here -->  
<router-outlet></router-outlet>  
  • routerLink is a directive that creates navigation links.
  • <router-outlet> acts as a placeholder for the current route’s component.

Test Routing

Run ng serve --open and click the links—you’ll now navigate between Home and Users!

Testing Your App

Angular provides built-in tools for testing:

  • Unit Tests: Run ng test to execute component tests (uses Jasmine and Karma).
  • End-to-End Tests: Run ng e2e to test user flows (uses Cypress or Protractor).

For beginners, focus on manual testing first: Use the browser’s developer tools (F12) to debug, and ensure all features work as expected.

Conclusion

You’ve built your first Angular app! 🎉 In this guide, you learned:

  • How to set up Angular and use the CLI.
  • The basics of components, modules, and project structure.
  • Data binding (interpolation, property/event binding, two-way binding).
  • Services and dependency injection for shared logic.
  • Routing to navigate between views.

Angular is a vast framework, but these fundamentals will help you explore more advanced topics like forms, HTTP requests, state management, and deployment.

References

Happy coding! 🚀