Angular: Build Your First Web App, Step by Step

What is Angular? Your First Steps in Web Development

Want to build dynamic, single-page applications? Angular, a powerful framework maintained by Google, is your tool. It’s a structured approach to web development, offering efficiency and scalability. But is it right for your project? Let’s find out.

1. Setting Up Your Development Environment

Before you start coding, you’ll need a few things installed on your machine. I always recommend starting with the latest versions, but verify compatibility with your existing projects if you have any.

  1. Node.js and npm: Angular requires Node.js, a JavaScript runtime environment. Download the latest LTS (Long Term Support) version from the Node.js website. npm (Node Package Manager) comes bundled with Node.js.
  2. Angular CLI: The Angular CLI (Command Line Interface) is a tool that simplifies creating, building, and testing Angular projects. Install it globally using npm:

npm install -g @angular/cli

After installation, verify the installation by checking the version:

ng --version

This should display the Angular CLI version and other relevant information.

Pro Tip: Consider using a Node version manager like nvm (Node Version Manager) to easily switch between different Node.js versions for different projects. This can prevent compatibility issues down the line.

2. Creating Your First Angular Project

Now that you have the Angular CLI installed, you can create a new project. Open your terminal or command prompt and navigate to the directory where you want to store your project. Then, use the following command:

ng new my-first-angular-app

The CLI will prompt you with a few questions:

  • “Would you like to add Angular routing?” – Choose “Yes” (y). Routing allows navigation between different views in your application.
  • “Which stylesheet format would you like to use?” – Choose “CSS” (or any other format you prefer, like SCSS or Sass).

The CLI will then create a new directory with the project name and install the necessary dependencies. This might take a few minutes.

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

cd my-first-angular-app

3. Running Your Angular Application

To run your Angular application, use the following command:

ng serve

This command builds your application and starts a development server. By default, the application will be available at http://localhost:4200/. Open your web browser and navigate to this address. You should see the default Angular welcome page.

Common Mistake: Forgetting to navigate into the project directory before running ng serve. If you run the command outside the project directory, it will not work.

Pro Tip: Add the --open flag to the ng serve command (ng serve --open) to automatically open your browser to the application’s URL.

4. Understanding the Angular Project Structure

The Angular CLI creates a well-structured project. Here’s a brief overview of the key files and directories:

  • src/: This directory contains the source code for your application.
  • src/app/: This directory contains the application’s components, modules, and services.
  • src/app/app.component.ts: This is the root component of your application.
  • src/app/app.component.html: This is the template (HTML) for the root component.
  • src/app/app.module.ts: This is the root module of your application. Modules organize related components, directives, and services.
  • angular.json: This file contains the configuration for the Angular CLI, including build settings, test settings, and more.
  • package.json: This file contains the project’s dependencies and scripts.

Take some time to explore these files and understand their purpose. Understanding the project structure is crucial for building and maintaining Angular applications.

5. Creating Your First Component

Components are the building blocks of Angular applications. They encapsulate the logic, data, and view for a specific part of the user interface. To create a new component, use the following command:

ng generate component my-new-component

This command creates a new directory src/app/my-new-component/ containing the following files:

  • my-new-component.component.ts: The component class.
  • my-new-component.component.html: The component template.
  • my-new-component.component.css: The component styles.
  • my-new-component.component.spec.ts: The component unit tests.

Open my-new-component.component.ts and you’ll see the basic structure of an Angular component:

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

@Component({

selector: 'app-my-new-component',

templateUrl: './my-new-component.component.html',

styleUrls: ['./my-new-component.component.css']

})

export class MyNewComponentComponent {

}

The @Component decorator configures the component, specifying its selector (the HTML tag used to render the component), template URL, and style URLs. The MyNewComponentComponent class contains the component’s logic.

Now, add a simple message to the component’s template (my-new-component.component.html):

<p>Hello from my new component!</p>

6. Displaying Your Component

To display your new component in the application, you need to add it to the template of another component. Let’s add it to the root component (src/app/app.component.html). Open app.component.html and add the following line:

<app-my-new-component></app-my-new-component>

This uses the selector app-my-new-component defined in the component’s decorator to render the component. Save the changes, and your browser should automatically refresh, displaying the message “Hello from my new component!”

Common Mistake: Forgetting to import the component into the module where you want to use it. If you get an error saying that the component is not recognized, make sure it’s declared in the declarations array of the module (usually app.module.ts).

7. Data Binding

Data binding is a core concept in Angular. It allows you to synchronize data between the component’s class and its template. Angular offers several types of data binding:

  • Interpolation: Displays data from the component class in the template.
  • Property Binding: Sets the value of an HTML element’s property.
  • Event Binding: Responds to events triggered by the user.
  • Two-Way Binding: Synchronizes data between the component class and the template, allowing changes in the template to update the component class, and vice versa.

Let’s demonstrate interpolation. Open my-new-component.component.ts and add a property to the component class:

export class MyNewComponentComponent {

message: string = 'Hello from my new component!';

}

Now, open my-new-component.component.html and use interpolation to display the message:

<p>{{ message }}</p>

The {{ message }} syntax tells Angular to display the value of the message property. Save the changes, and your browser should now display “Hello from my new component!”

8. Working with Directives

Directives are instructions in the DOM (Document Object Model) that tell Angular how to transform the DOM. Angular provides several built-in directives, including:

  • *ngIf: Conditionally adds or removes an element from the DOM.
  • *ngFor: Repeats an element for each item in a list.
  • [ngClass]: Adds or removes CSS classes based on a condition.
  • [ngStyle]: Applies CSS styles based on a condition.

Let’s use *ngIf to conditionally display a message. Open my-new-component.component.ts and add a property to the component class:

export class MyNewComponentComponent {

message: string = 'Hello from my new component!';

showGreeting: boolean = true;

}

Now, open my-new-component.component.html and use *ngIf to conditionally display the message:

<p *ngIf="showGreeting">{{ message }}</p>

If showGreeting is true, the message will be displayed. If it’s false, the message will not be displayed. Try changing the value of showGreeting in the component class to see the effect.

Pro Tip: When using structural directives like *ngIf and *ngFor, remember that they create a new scope. This can affect how you access variables within the directive. You might also find value in reading more about Angular for non-techies to better understand the fundamentals.

9. Services and Dependency Injection

Services are classes that encapsulate reusable logic. They are often used to fetch data from a server, perform calculations, or manage state. Dependency injection (DI) is a design pattern that allows you to inject dependencies (services) into other classes (components, services, etc.).

To create a new service, use the following command:

ng generate service my-new-service

This command creates a new file src/app/my-new-service.service.ts. Open this file and you’ll see the basic structure of an Angular service:

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

@Injectable({

providedIn: 'root'

})

export class MyNewServiceService {

constructor() { }

}

The @Injectable decorator indicates that the service can be injected into other classes. The providedIn: 'root' option specifies that the service should be provided in the root injector, making it available throughout the application.

Let’s add a simple method to the service:

export class MyNewServiceService {

constructor() { }

getGreeting(): string {

return 'Hello from my new service!';

}

}

Now, let’s inject this service into a component. Open my-new-component.component.ts and add the following code:

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

import { MyNewServiceService } from '../my-new-service.service';

@Component({

selector: 'app-my-new-component',

templateUrl: './my-new-component.component.html',

styleUrls: ['./my-new-component.component.css']

})

export class MyNewComponentComponent implements OnInit {

message: string = 'Hello from my new component!';

showGreeting: boolean = true;

greetingFromService: string = '';

constructor(private myNewService: MyNewServiceService) { }

ngOnInit(): void {

this.greetingFromService = this.myNewService.getGreeting();

}

}

We import the service, inject it into the component’s constructor, and then call the getGreeting() method in the ngOnInit() lifecycle hook. The ngOnInit() hook is called after the component is initialized.

Finally, open my-new-component.component.html and display the greeting from the service:

<p *ngIf="showGreeting">{{ message }}</p>

<p>{{ greetingFromService }}</p>

Your browser should now display “Hello from my new service!”

Common Mistake: Forgetting to add the service to the constructor of the component. If you get an error saying that the service cannot be found, make sure you’ve added it to the constructor with the private keyword.

I had a client last year who was struggling with dependency injection. They kept getting errors because they were trying to inject a service into a component without adding it to the constructor. Once I explained the concept of dependency injection and showed them how to properly inject the service, they were able to resolve the issue and move forward with their project. For more practical tips to boost your tech productivity, check out this article.

10. Routing and Navigation

Routing allows you to navigate between different views in your application. When you created your Angular project, you chose to add Angular routing. This created a src/app/app-routing.module.ts file. Let’s configure some routes.

First, create two new components: home and about.

ng generate component home

ng generate component about

Now, open src/app/app-routing.module.ts and add the following routes:

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

import { RouterModule, Routes } from '@angular/router';

import { HomeComponent } from './home/home.component';

import { AboutComponent } from './about/about.component';

const routes: Routes = [

{ path: 'home', component: HomeComponent },

{ path: 'about', component: AboutComponent },

{ path: '', redirectTo: '/home', pathMatch: 'full' } // Redirect to home

];

@NgModule({

imports: [RouterModule.forRoot(routes)],

exports: [RouterModule]

})

export class AppRoutingModule { }

This defines three routes: /home, /about, and a default route that redirects to /home. Now, open src/app/app.component.html and add the following code:

<nav>

<a routerLink="/home" routerLinkActive="active">Home</a>

<a routerLink="/about" routerLinkActive="active">About</a>

</nav>

<router-outlet></router-outlet>

The routerLink directive creates links to the different routes. The routerLinkActive directive adds the class “active” to the active link. The <router-outlet> element is where the routed components will be displayed.

Save the changes, and you should now see the navigation links in your browser. Clicking on the links will navigate to the corresponding components. If you are looking to build faster with other tutorial-rich tech, explore Vue.js as well.

Pro Tip: Use lazy loading for your routes to improve the initial load time of your application. Lazy loading loads modules only when they are needed, reducing the initial bundle size. Also, remember that JavaScript myths can hinder your development, so stay informed.

What are the advantages of using Angular?

Angular offers a structured development approach, improved code maintainability, enhanced testability, and increased development speed. Its component-based architecture promotes reusability.

Is Angular difficult to learn?

Angular has a steeper learning curve compared to some other frameworks, primarily due to its complexity and reliance on TypeScript. However, with dedicated effort and practice, it can be mastered.

What is TypeScript, and why is it used in Angular?

TypeScript is a superset of JavaScript that adds static typing. Angular uses TypeScript to improve code quality, provide better tooling support, and catch errors during development rather than at runtime.

How do I deploy an Angular application?

Deploying an Angular application typically involves building the application using the ng build --prod command and then deploying the resulting files to a web server, such as Apache or Nginx, or a cloud platform like Google Cloud or AWS.

What are Angular modules?

Angular modules are containers that group related components, directives, and services. They help organize the application into logical units and define the dependencies required for those units.

This is just the beginning. Angular is a powerful framework with many more features to explore. But with these basics, you’re well on your way to building amazing web applications. The best way to learn is by doing – start building something today!

Kwame Nkosi

Lead Cloud Architect Certified Cloud Solutions Professional (CCSP)

Kwame Nkosi is a Lead Cloud Architect at InnovAI Solutions, specializing in scalable infrastructure and distributed systems. He has over 12 years of experience designing and implementing robust cloud solutions for diverse industries. Kwame's expertise encompasses cloud migration strategies, DevOps automation, and serverless architectures. He is a frequent speaker at industry conferences and workshops, sharing his insights on cutting-edge cloud technologies. Notably, Kwame led the development of the 'Project Nimbus' initiative at InnovAI, resulting in a 30% reduction in infrastructure costs for the company's core services, and he also provides expert consulting services at Quantum Leap Technologies.