Building a project using Angular and NestJS is a great way to create a robust, full-stack web application. Angular, a popular frontend JavaScript framework, offers a complete set of features for building rich, interactive user interfaces. In contrast, NestJS, a backend framework built with Node.js, provides a robust set of tools for building efficient and scalable server-side applications.
Together, these two frameworks provide a complete solution for building modern web applications, from the frontend user interface to the server-side backend logic. In this tutorial, we will learn how to use Angular and NestJS to build a project, including setting up the development environment, creating components and services, handling routing, and making API calls.
This tutorial will provide you with a comprehensive understanding of how to use Angular and NestJS to build web applications. After reading this article, you’ll be able to create your own projects using this powerful stack.
Jump ahead:
To get started with this tutorial, ensure you have the following:
NestJS and Angular are both web application frameworks that are based on JavaScript and use JavaScript as their primary programming language. Both frameworks also share the following features:
However, there are some differences:
NestJS and Angular complement each other well in full-stack web development. Together, they can create a complete web application with a robust backend and a dynamic, interactive frontend.
To set up a NestJS project, you’ll need to first install the NestJS CLI tool, like so:
npm i -g @nestjs/cli
Next, create a new project by running the following command with the project name of your choice. For this tutorial, we’re using tasks
as the project name:
nest new tasks
This command will prompt you to choose the package to manage for your project. For example, you can select between npm and Yarn. For this tutorial, we’ll use npm. Once you’ve selected your preferred package manager, the project’s dependencies will be installed.
Now, navigate to the project directory and run the development server:
cd tasks npm run start:dev
Once the development server is running, you should see a “Hello World!” message by navigating to http://localhost:3000 in your browser.
Now that your NestJS project is set up, you can create a new Angular project for the application’s frontend.
Start by installing the Angular CLI by running the following command in your terminal:
npm install -g @angular/cli
Next, create a new project by running the following command with the project name of your choice. For this demonstration, we’re using tasks-ui
as the project name:
ng
tasks-ui
Now navigate to the project directory and install the project dependencies:
cd tasks-ui npm install <
Finally, use the following command to run the development:
ng serve
Once the development server is running, you should be able to see the default Angular application by navigating to http://localhost:4200 in your browser.
Now that you’ve both the backend and frontend servers set up, it’s time to create the task application to save and display your list of daily tasks.
To begin, you’ll create the backend APIs. This will include creating routes, controllers, and services to handle the task data, as well as the CRUD operations.
Start by creating a tasks.json
file in the root directory of your project. This file will serve as a database to store your task records.
Next, update the src/app.service.ts
file with the following code:
import { Injectable } from '@nestjs/common'; import * as fs from 'fs'; export interface Tasks { id: number; name: string; completed: boolean; } @Injectable() export class AppService { private tasks: Array<Tasks>; constructor() { this.tasks = JSON.parse(fs.readFileSync('tasks.json', 'utf8')); } getTasks(): Tasks[] { return this.tasks; } createTask(name: string): Tasks[] { const task = { id: this.tasks.length + 1, name, completed: false }; this.tasks = [...this.tasks, { ...task}]; fs.writeFileSync('tasks.json', JSON.stringify(this.tasks)); return this.tasks; } deleteTask(id: number): Tasks[] { const index = this.tasks.findIndex((task) => task.id === id); this.tasks.splice(index, 1); return this.tasks; } }
This code implements a service that allows you to manage a list of tasks. The service utilizes the @nestjs/common
module to provide decorators and utility functions for NestJS and the fs
module to interact with the file system.
A Tasks
interface
is defined to structure each task object the service will manage. The @Injectable()
decorator is used to make the AppService
class injectable.
A private property, tasks
, is defined to hold an array of Tasks
objects and is initialized in the constructor by reading the tasks from the tasks.json
file and parsing it into an array of Tasks objects. The service has three methods:
getTasks()
: Returns the current list of taskscreateTask(name: string)
: Creates a new task
object with a given name, adds it to the list of tasks, and then writes the updated list to the tasks.json
filedeleteTask(id: number)
: Deletes a task from the list based on the given id
The controller in NestJS is responsible for handling incoming HTTP requests and returning the appropriate response. It acts as an intermediary between the client and the service, receiving input from the client, processing it, and then returning a response.
To create a controller for the application, you’ll need to define the routes and methods for handling different requests. This will allow our application to handle various types of client requests such as GET, POST, PUT, and DELETE.
To create controllers for the AppService
, update the src/app.controllers.ts
file with the following code:
import { Controller, Get, Post, Body, Delete, Param, HttpException, HttpStatus, } from '@nestjs/common'; import { AppService } from './app.service'; import { Tasks } from './app.service'; @Controller('api/todos') export class AppController { constructor(private readonly appService: AppService) {} @Get() getTodos(): Tasks[] { try { return this.appService.getTasks(); } catch (error) { throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); } } @Post() createTodo(@Body() { name }: Tasks): Tasks[] { try { return this.appService.createTask(name); } catch (error) { throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); } } @Delete(':id') deleteTodo(@Param('id') id: number): Tasks[] { try { return this.appService.deleteTask(id); } catch (error) { throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR); } } }
This code defines a controller for handling tasks related requests in a NestJS application. The controller is decorated with the @Controller
decorator, which is imported from @nestjs/common
.
The decorator takes in a string argument, which defines the endpoint for the controller. In this case, the endpoint is api/tasks
. The code also imports other decorators such as @Get
, @Post
, @Body
, @Delete
, and @Param
which are used to handle different types of requests and extract data from the request.
The AppService
is imported because it is a dependency and is used to handle the application’s logic. The controller has three methods: getTasks()
, createTask()
, and deleteTask()
.
Each method is decorated with a decorator corresponding to the type of HTTP request it handles. The getTasks()
method is decorated with @Get()
and returns a list of tasks by calling the getTasks()
method of the AppService
.
The createTasks()
method is decorated with @Post()
and @Body()
. It creates a new task by calling the createTask()
method of the AppService
and passing in the name of the task.
The deleteTask()
method is decorated with @Delete()
and @Param()
. It deletes a task by calling the deleteTask()
method of the AppService
and passing in the task id
.
The methods also include error handling by using try-catch blocks and throwing a HttpException
with HttpStatus.INTERNAL_SERVER_ERROR
when an error occurs.
Now that the task API is complete, you’ve successfully finished building the backend part of the application!
Now it’s time to create the application‘s UI using Angular and then consume the API to manage tasks from the user interface.
First, generate the service of a task with the following command:
ng generate service tasks
This command creates a new service file in the src/app
directory with the name of the service and also registers it in the app.module.t
s file.
Next, update tasks.service.ts
file with code snippets below to add the services to consume the NestJS APIs:
import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { map } from 'rxjs'; @Injectable({ providedIn: 'root', }) export class TaskService { host = 'http://localhost:3000/api'; // eslint-disable-next-line @typescript-eslint/no-empty-function constructor(private http: HttpClient) {} getTasks() { return this.http.get(`${this.host}/tasks`).pipe(map((res) => res)); } addTask(todo: string) { return this.http.post(`${this.host}/tasks`, { name: todo, completed: false, }); } deleteTask(id: number) { return this.http.delete(`${this.host}/tasks/${id}`); } }
The above code defines a service in Angular for handling functionality-related tasks. The service is decorated with the @Injectable
decorator, which is imported from @angular/core
.
The service has a host
property that holds the base URL of the backend API. In addition, the HttpClient
module is imported to make HTTP requests to the backend.
The service has three methods: getTasks()
, addTask()
, and deleteTask()
. The getTasks()
method makes a GET request to the backend to retrieve the tasks. The addTask()
method makes a POST request to the backend to add a new task. The deleteTask()
method makes a DELETE request to the backend to delete a specific task.
Each method uses the HttpClient
module to make the corresponding HTTP request to the backend and returns the response. The map
operator extracts the response from the observable interface.
Next, update the app.components.ts
file with the following code to subscribe to the service that you just created:
import { Component } from '@angular/core'; import { TaskService } from './todo.service'; interface Task { id: number; name: string; completed: boolean; } @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'], }) export class AppComponent { tasks: Task[]; task: string; // eslint-disable-next-line @typescript-eslint/no-empty-function constructor( private taskService: TaskService, ) { this.tasks = []; this.task = ''; } title = 'task-ui'; ngOnInit() { this.taskService.getTasks().subscribe((data) => { console.log(data); this.tasks = data as Task[]; }); } addTask(task: string) { this.taskService.addTask(task).subscribe(); this.task =''; } deleteTask(id: number) { this.taskService.deleteTask(id).subscribe((data) => { console.log(data); }); } }
The above code defines an AppComponent
class. The AppComponent
is decorated with the @Component
decorator, which is imported from @angular/core
. It has a selector
, templateUrl
, and styleUrls
properties that are used to specify the component’s selector, template, and styles, respectively.
The TaskService
is imported and injected into the component’s constructor.
The component has three properties:
tasks
: Array of Task
objectstask
: Used to store the task that the user wants to addtitle
: Used to store the title of the applicationThe ngOnInit()
method is called when the TaskService
component is initialized. This component has three methods:
getTasks()
: Called to retrieve the tasks from the backendaddTask()
: Called when the user wants to add a new task to the backenddeleteTask()
: Called when the user wants to delete a task from the backendLet’s take advantage of the methods and variables defined in the AppComponent
to display the tasks returned from the API and to attach event handlers to submit a form to add a new task and to delete an existing task.
Update the app.component.html
file with the following code:
<html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css" rel= "stylesheet" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.8.3/angular.min.js"></script> <title>Document</title> </head> <body> <div class="main" ng-app="mytodo" ng-controller="myCtrl"> <h1>Todo List App</h1> <div class="search"> <input type="text" [(ngModel)]="task" /> <span (click)="addTask(task)"><i class="fas fa-plus"></i></span> </div> <ul> <li *ngFor= "let task of tasks"> {{ task.name }}<i class="fas fa-trash-alt" (click)="deleteTask(task.id)"></i> </li> </ul> <p></p> </div> </body> </html>
This code is a part of the AppComponent
template. It includes an input field, a button, and an unordered list. The input field is bound to the task
property of the component using the ngModel
directive.
The value of the input field is two-way bound to the task
property, so when the user types into the input field, the value of the task
property updates, and when the value of the task
property is updated, the input field updates.
The button element has an icon and an event binding to the addTask()
component method using the (click)
event. When a user clicks on this icon, the addTask()
method is called with the task text.
The unordered list iterates over the tasks
array using the ngFor
directive. This directive creates a new list item element for each task in the tasks
array and binds the task data to the task
variable. Each list item element displays the task name and has a trash icon with an event binding to the deleteTask()
method of the component using the (click)
event. When a user clicks on the trash icon, the deleteTask()
method is called with the task id
.
To enhance the appearance of your application, update the styles in the src/styles.css
file with the following stylesheets:
body{ justify-content: center; display: flex; font-family: 'Poppins', sans-serif; } .main{ width: 500px; padding: 15p; background-color: #ededed ; } h1{ text-align: center; color: #e69d17; margin: 10px; } input[type=text]{ width: 90%; padding: 10px; font-size: 16px; margin-left: 8px; border-radius: 3px; border: none; outline: none; } .search { position: relative; } .search span{ position: absolute; top: -10px; right: -4px; background: #e69d17; padding: 20px; display: flex; border-radius: 50%; width: 15px; height: 15px; cursor: pointer; } .search span i{ line-height: -100%; } ul { padding: 2px; list-style: none; } ul li { background-color: #fff; margin: 5px; padding: 10px; border-right: 4px solid #e69d17; border-left: 4px solid #e69d17; } ul li i { padding: 4px; float: right; cursor: pointer; } p{ color: red; text-align: center; }
The above stylesheet will style the input fields and position the add (+) button next to the fields. It will also format the tasks in rows and add a delete (trash) icon beside each task item.
Now it’s time to verify that your application is functioning correctly. Before running the application, you’ll need to enable a proxy to prevent CORS (Cross-Origin Resource Sharing) issues. A proxy acts as a middleman for requests from clients trying to access resources from other servers. This can improve network performance, security, and compliance.
To enable a proxy, create a file named proxy.config.json
in your src
directory and add the following configurations:
{ "/api": { "target": "http://localhost:3000", "secure": false, "pathRewrite": {"^/api" : ""} } }
Now run the backend and frontend development servers, and navigate to http://localhost:4200/ to preview the frontend:
You can add more tasks by clicking on the + icon, and delete a task by clicking on the trash icon.
In this tutorial, we walked through how to build a project using Angular and NestJS. We began by explaining the similarities between the two frameworks. Then, we set up development servers for NestJS and Angular. Next, we created a NestJS service that wrote data to a JSON file, serving as the application’s database. We then implemented an Angular service that sent API requests to the NestJS backend to perform CRUD operations.
Finally, we updated the Angular App component class to create methods allowing data manipulation from the App template. Now that you have learned how to integrate Angular and NestJS in building a full-stack application, you can use these frameworks in your next project. You can also update the backend to use an actual database like MongoDB or MySQL by cloning the full project from GitHub.
I hope you found this tutorial helpful and gave you some ideas on using Angular and NestJS in your next project. Happy coding!
Debugging Angular applications can be difficult, especially when users experience issues that are difficult to reproduce. If you’re interested in monitoring and tracking Angular state and actions for all of your users in production, try LogRocket.
LogRocket is like a DVR for web and mobile apps, recording literally everything that happens on your site including network requests, JavaScript errors, and much more. Instead of guessing why problems happen, you can aggregate and report on what state your application was in when an issue occurred.
The LogRocket NgRx plugin logs Angular state and actions to the LogRocket console, giving you context around what led to an error, and what state the application was in when an issue occurred.
Modernize how you debug your Angular apps — start monitoring for free.
Hey there, want to help make our blog better?
Join LogRocket’s Content Advisory Board. You’ll help inform the type of content we create and get access to exclusive meetups, social accreditation, and swag.
Sign up nowThe useReducer React Hook is a good alternative to tools like Redux, Recoil, or MobX.
Node.js v22.5.0 introduced a native SQLite module, which is is similar to what other JavaScript runtimes like Deno and Bun already have.
Understanding and supporting pinch, text, and browser zoom significantly enhances the user experience. Let’s explore a few ways to do so.
Playwright is a popular framework for automating and testing web applications across multiple browsers in JavaScript, Python, Java, and C#. […]