DEV Community

Cover image for Building a Scalable Web App with Angular: A Comprehensive Guide
3a5abi 🥷
3a5abi 🥷

Posted on • Originally published at devtoys.io

Building a Scalable Web App with Angular: A Comprehensive Guide

Angular is a popular front-end framework developed and maintained by Google. It provides a powerful toolset for building dynamic, single-page web applications (SPAs) with a clean, maintainable structure. This tutorial will guide you through creating a simple yet comprehensive Angular application, covering core concepts and demonstrating how to implement various features.


Prerequisites

Before we dive into Angular, ensure you have the following installed:

- Node.js (version 12 or higher)
- npm or yarn
- Angular CLI
Enter fullscreen mode Exit fullscreen mode

Step 1: Setting Up Your Angular Project

Start by installing the Angular CLI globally:

npm install -g @angular/cli
Enter fullscreen mode Exit fullscreen mode

Create a new Angular project using the CLI:

ng new my-angular-app
Enter fullscreen mode Exit fullscreen mode

Navigate to your project directory:

cd my-angular-app
Enter fullscreen mode Exit fullscreen mode

Serve the application:

ng serve
Enter fullscreen mode Exit fullscreen mode

Visit http://localhost:4200 to see your Angular application in action.


Step 2: Understanding the Project Structure

Angular projects follow a modular architecture. Here’s a brief overview of the default structure:

- src/: Contains your application's source code.
    - app/: The main application module and components.
        - app.component.ts: The root component of the application.
        - app.config.ts: Configuration file for the application.
        - app.routes.ts: Contains the routes configuration.
    - assets/: Contains static assets like images and styles.
    - environments/: Contains environment-specific configurations.
Enter fullscreen mode Exit fullscreen mode

Step 3: Creating Your First Component

Components are the fundamental building blocks of an Angular application. Create a new component called users:

ng generate component users
Enter fullscreen mode Exit fullscreen mode

This will generate a users directory inside the src/app folder with the following files:

users.component.ts
users.component.html
users.component.css
users.component.spec.ts
Enter fullscreen mode Exit fullscreen mode

Step 4: Creating a Service

Services in Angular are used to handle business logic and data management. Create a new service called users:

ng generate service users
Enter fullscreen mode Exit fullscreen mode

👀 Are you enjoying this tutorial? If so, come swing by our community to explorer further! ===> DevToys.io


Step 5: Implementing the Users Service

Open src/app/users.service.ts and implement basic CRUD operations:

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

export interface User {
  id: number;
  name: string;
  age: number;
}

@Injectable({
  providedIn: 'root'
})
export class UsersService {
  private users: User[] = [];

  getAllUsers(): User[] {
    return this.users;
  }

  getUserById(id: number): User | undefined {
    return this.users.find(user => user.id === id);
  }

  addUser(user: User) {
    this.users.push(user);
  }

  updateUser(id: number, updatedUser: User) {
    const index = this.users.findIndex(user => user.id === id);
    if (index > -1) {
      this.users[index] = updatedUser;
    }
  }

  deleteUser(id: number) {
    this.users = this.users.filter(user => user.id !== id);
  }
}
Enter fullscreen mode Exit fullscreen mode

Step 6: Implementing the Users Component

Open src/app/users/users.component.ts and connect the service to handle data display:

import { Component, OnInit } from '@angular/core';
import { UsersService, User } from '../users.service';

@Component({
  selector: 'app-users',
  standalone: true,
  imports: [
    NgForOf
  ],
  templateUrl: './users.component.html',
  styleUrls: ['./users.component.css']
})
export class UsersComponent implements OnInit {
  users: User[] = [];

  constructor(private usersService: UsersService) {}

  ngOnInit(): void {
    this.users = this.usersService.getAllUsers();
  }

   addUser(name: string, age: number): void {
    const newUser: User = { id: Date.now(), name, age: Number(age) };
    this.usersService.addUser(newUser);
    this.users = this.usersService.getAllUsers();
  }
}
Enter fullscreen mode Exit fullscreen mode

In the src/app/users/users.component.html file, add the following code to display the users:

<div>
  <input #userName type="text" placeholder="Name">
  <input #userAge type="number" placeholder="Age">
  <button (click)="addUser(userName.value, userAge.value)">Add User</button>
</div>

<div *ngFor="let user of users">
  <p>{{ user.name }} ({{ user.age }} years old)</p>
</div>
Enter fullscreen mode Exit fullscreen mode

Step 7: Setting Up Routing

To navigate to the Users page, you need to set up routing in your Angular application.

Open src/app/app.routes.ts and set up your routes:

import { Routes } from '@angular/router';
import { UsersComponent } from './users/users.component';

export const routes: Routes = [
  { path: 'users', component: UsersComponent },
  { path: '', redirectTo: '/users', pathMatch: 'full' } // Redirect to users page by default
];
Enter fullscreen mode Exit fullscreen mode

Step 8: Configure the Application

Open src/app/app.config.ts and ensure the provideRouter is configured:

import { ApplicationConfig, provideZoneChangeDetection } from '@angular/core';
import { provideRouter } from '@angular/router';

import { routes } from './app.routes';

export const appConfig: ApplicationConfig = {
  providers: [provideZoneChangeDetection({ eventCoalescing: true }), provideRouter(routes)]
};
Enter fullscreen mode Exit fullscreen mode

Step 9: Add Router Outlet and Navigation Links

In your app.component.ts, ensure that RouterOutlet and RouterLink are imported and configured:

import { Component } from '@angular/core';
import { RouterLink, RouterOutlet } from '@angular/router';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [RouterOutlet, RouterLink],
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'my-angular-app';
}
Enter fullscreen mode Exit fullscreen mode

In your app.component.html, add the directive and navigation link

<nav>
  <a routerLink="/users">Users</a>
</nav>

<router-outlet></router-outlet>
Enter fullscreen mode Exit fullscreen mode

Step 10: Running the Application

Now, when you run your application:

ng serve
Enter fullscreen mode Exit fullscreen mode

You can navigate to the Users page by going to http://localhost:4200/users in your browser or by clicking the “Users” link in your navigation.


Conclusion

🎉 Congratulations! You’ve created a basic Angular application with CRUD functionality and set up routing to navigate to your Users page. This tutorial covers the foundational concepts of Angular, but there’s much more to explore. Angular offers powerful features like:

  • Reactive Forms: Create complex forms with ease and manage form validation.
  • HTTP Client: Communicate with backend services to fetch and send data.
  • State Management: Manage state effectively in your application using libraries like NgRx.
  • Lazy Loading: Optimize your application’s performance by loading modules only when needed.
  • Authentication and Authorization: Implement user authentication and manage access control.
  • Testing: Use Angular’s robust testing tools to write unit and end-to-end tests.

Dive into the official documentation to continue your journey and build more advanced applications with Angular. Happy coding!

👋🏼 If you want to find more articles like this, come check us out at DevToys.io

Top comments (2)

Collapse
 
n3rdnerd profile image
N3rdNERD

Cool Step by step instruction.

Collapse
 
3a5abi profile image
3a5abi 🥷

Thanks!