Clara Ekekenta Software Engineer and perpetual learner with a passion for OS and expertise in Python, JavaScript, Go, Rust, and Web 3.0.

Build a project using Angular and NestJS

10 min read 2859 107

Build Project Using Angular NestJS

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:

  • Node.js and npm installed

Similarities between Angular and NestJS

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:

  • Use a component-based architecture to organize and modularize code
  • Use TypeScript, a typed superset of JavaScript. This allows for catching errors early in the development process and makes the code more maintainable
  • Provide potent tools for building dynamic and interactive user interfaces

However, there are some differences:

  • NestJS is built on top of ExpressJS, a popular Node.js web framework, while Angular uses the MVC (Model-View-Controller) pattern to build applications
  • NestJS is a backend framework, while Angular is a frontend framework

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.

Setting up the NestJS project

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.

Setting up a new Angular project

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.

Creating the task application

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.

Creating the service

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;
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) => === 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 tasks
  • createTask(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 file
  • deleteTask(id: number): Deletes a task from the list based on the given id

Creating the controller

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 {
} from '@nestjs/common';
import { AppService } from './app.service';
import { Tasks } from './app.service';
export class AppController {
  constructor(private readonly appService: AppService) {}
  getTodos(): Tasks[] {
    try {
      return this.appService.getTasks();
    } catch (error) {
      throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR);
  createTodo(@Body() { name }: Tasks): Tasks[] {
    try {
      return this.appService.createTask(name);
    } catch (error) {
      throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR);
  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.

More great articles from LogRocket:

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.

Creating the application user interface

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.

Creating the Angular service

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.ts 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';
  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(`${}/tasks`).pipe(map((res) => res));
  addTask(todo: string) {
    return`${}/tasks`, {
      name: todo,
      completed: false,
  deleteTask(id: number) {
    return this.http.delete(`${}/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.

Updating the app component

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;
  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
    private taskService: TaskService,
  ) {
    this.tasks = [];
    this.task = '';
  title = 'task-ui';
  ngOnInit() {
    this.taskService.getTasks().subscribe((data) => {
      this.tasks = data as Task[];

  addTask(task: string) {
    this.task ='';

  deleteTask(id: number) {
    this.taskService.deleteTask(id).subscribe((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 objects
  • task: Used to store the task that the user wants to add
  • title: Used to store the title of the application

The ngOnInit() method is called when the TaskService component is initialized. This component has three methods:

  • getTasks(): Called to retrieve the tasks from the backend
  • addTask(): Called when the user wants to add a new task to the backend
  • deleteTask(): Called when the user wants to delete a task from the backend

Updating the app template

Let’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">
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
      rel= "stylesheet"
    <script src=""></script>
    <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>
        <li *ngFor= "let task of tasks">
          }}<i class="fas fa-trash-alt" (click)="deleteTask("></i>

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.

Updating the styling

To enhance the appearance of your application, update the styles in the src/styles.css file with the following stylesheets:

    justify-content: center;
    display: flex;
    font-family: 'Poppins', sans-serif;
    width: 500px;
    padding: 15p;
    background-color: #ededed  ;
    text-align: center;
    color: #e69d17;
    margin: 10px;
    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;
    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.

Testing the full-stack application

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:

Full-stack Angular NestJS Application

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!

Experience your Angular apps exactly how a user does

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 - .

Clara Ekekenta Software Engineer and perpetual learner with a passion for OS and expertise in Python, JavaScript, Go, Rust, and Web 3.0.

Leave a Reply