How to Set Up Angular Project

How to Set Up an Angular Project Angular is one of the most powerful and widely adopted front-end frameworks for building dynamic, scalable, and high-performance web applications. Developed and maintained by Google, Angular provides a comprehensive solution for modern web development, including two-way data binding, dependency injection, reactive forms, routing, and a robust CLI for project scaffo

Nov 10, 2025 - 08:45
Nov 10, 2025 - 08:45
 1

How to Set Up an Angular Project

Angular is one of the most powerful and widely adopted front-end frameworks for building dynamic, scalable, and high-performance web applications. Developed and maintained by Google, Angular provides a comprehensive solution for modern web development, including two-way data binding, dependency injection, reactive forms, routing, and a robust CLI for project scaffolding. Setting up an Angular project correctly from the start is criticalnot only for ensuring a smooth development workflow but also for maintaining code quality, performance, and scalability as your application grows.

Many developers, especially those new to Angular, encounter issues during initial setupsuch as version conflicts, missing dependencies, or misconfigured environmentsthat can derail progress before a single line of application code is written. This tutorial provides a complete, step-by-step guide to setting up an Angular project from scratch, covering everything from prerequisite installations to final project verification. Whether you're building a personal portfolio, a startup MVP, or an enterprise-grade application, this guide ensures your Angular project begins on solid ground.

Step-by-Step Guide

Prerequisites: What You Need Before Starting

Before you begin setting up your Angular project, ensure your development environment meets the following requirements:

  • Node.js (version 18 or higher recommended)
  • NPM (Node Package Manager) or Yarn (optional but supported)
  • Code Editor (Visual Studio Code is highly recommended)
  • Internet Connection (to download packages and dependencies)

Angular relies on Node.js to run its CLI and build tools. NPM comes bundled with Node.js, so installing Node.js automatically installs NPM. To verify that Node.js and NPM are installed correctly, open your terminal or command prompt and run:

node -v

npm -v

If both commands return version numbers (e.g., v18.17.0 and 9.6.7), you're ready to proceed. If not, download and install the latest LTS (Long-Term Support) version of Node.js from https://nodejs.org.

Step 1: Install the Angular CLI Globally

The Angular Command Line Interface (CLI) is the official tool for creating, developing, scaffolding, and maintaining Angular applications. It automates repetitive tasks such as generating components, services, modules, and tests, and ensures consistency across projects.

To install the Angular CLI globally, run the following command in your terminal:

npm install -g @angular/cli

The -g flag installs the CLI globally on your system, making it accessible from any directory. This step only needs to be done once per machine.

After installation, verify the CLI is installed correctly by running:

ng version

You should see output similar to:

Angular CLI: 17.3.0

Node: 18.17.0

Package Manager: npm 9.6.7

OS: darwin x64

Angular:

...

Package Version

------------------------------------------------------

@angular/core 17.3.0

@angular/cli 17.3.0

If you encounter permission errors during installation, consider using a Node version manager like nvm (Node Version Manager) to avoid system-wide permission issues. Install nvm via:

curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash

Then restart your terminal and install Node.js using nvm:

nvm install --lts

nvm use --lts

Step 2: Create a New Angular Project

With the Angular CLI installed, you can now generate a new project. Navigate to the directory where you want to create your project, then run:

ng new my-angular-app

Replace my-angular-app with your desired project name. The CLI will prompt you with two configuration questions:

  1. Would you like to add Angular routing? Type y if your app will have multiple views or pages (e.g., Home, About, Contact). This generates a app-routing.module.ts file to handle navigation.
  2. Which stylesheet format would you like to use? Choose from CSS, SCSS, SASS, Less, or Stylus. SCSS is recommended for its advanced features like variables, nesting, and mixins, and is widely adopted in enterprise projects.

For most projects, select y for routing and SCSS for styles. The CLI will then begin downloading dependencies and scaffolding the project structure. This process may take a few minutes depending on your internet speed.

Step 3: Understand the Project Structure

Once the project is created, navigate into the project folder:

cd my-angular-app

Use your code editor to explore the generated folder structure. Heres what each key file and folder does:

  • src/ The main source directory containing all application code.
  • src/app/ Contains Angular modules, components, services, and routing.
  • src/app/app.component.html The root component template.
  • src/app/app.component.ts The TypeScript logic for the root component.
  • src/app/app.component.scss Styles scoped to the root component.
  • src/app/app.module.ts The root module that bootstraps the application (in Angular 16+, this is optional due to standalone components).
  • src/app/app-routing.module.ts Defines routes for navigation (if routing was enabled).
  • src/index.html The main HTML file where Angular renders the app.
  • src/main.ts The entry point that bootstraps the application.
  • angular.json Configuration file for the Angular CLI, including build, test, and serve settings.
  • package.json Lists project dependencies and scripts.
  • tsconfig.json TypeScript compiler options.

Understanding this structure is essential for navigating and extending your application efficiently.

Step 4: Run the Development Server

After project creation, start the development server to view your application in the browser:

ng serve

By default, this command compiles the application and serves it on http://localhost:4200. Open your browser and navigate to that URL. You should see the default Angular welcome page with the message Welcome to my-angular-app!

The ng serve command also enables live reloading. Any changes you make to your source files (HTML, TypeScript, or SCSS) are automatically detected and reflected in the browser without requiring a manual refresh.

To customize the port or disable live reload, use additional flags:

ng serve --port 4300 --live-reload false

Step 5: Generate a Component Using the CLI

One of the biggest advantages of the Angular CLI is its ability to generate boilerplate code. To create a new component, run:

ng generate component hero-list

Or use the shorthand:

ng g c hero-list

The CLI creates a new folder named hero-list inside src/app/, containing four files:

  • hero-list.component.html Template file
  • hero-list.component.ts Component logic
  • hero-list.component.scss Styles
  • hero-list.component.spec.ts Unit test file

Angular automatically registers the component in the nearest module (usually app.module.ts or as a standalone component). If you're using Angular 16+ with standalone components, the component will be marked with standalone: true in the decorator.

To use the component in your app, open app.component.html and add:

<app-hero-list></app-hero-list>

Save the file and observe the live reload in your browser. The new component now renders on the page.

Step 6: Add Services and Dependency Injection

Services are used to share logic and data across components. Create a service using:

ng generate service services/hero

This generates hero.service.ts inside a new services/ folder. Open the file and define a simple method:

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

@Injectable({

providedIn: 'root'

})

export class HeroService {

getHeroes(): string[] {

return ['Iron Man', 'Captain America', 'Thor'];

}

}

The @Injectable({ providedIn: 'root' }) decorator makes this service available application-wide without needing to declare it in a module.

Now inject the service into your component. In hero-list.component.ts:

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

import { HeroService } from '../services/hero.service';

@Component({

selector: 'app-hero-list',

templateUrl: './hero-list.component.html',

styleUrls: ['./hero-list.component.scss']

})

export class HeroListComponent implements OnInit {

heroes: string[] = [];

constructor(private heroService: HeroService) { }

ngOnInit(): void {

this.heroes = this.heroService.getHeroes();

}

}

Then display the list in hero-list.component.html:

<ul>

<li *ngFor="let hero of heroes">{{ hero }}</li>

</ul>

Save and refresh the browser. Youll now see the list of heroes rendered dynamically.

Step 7: Configure Environment Variables

For different deployment environments (development, staging, production), Angular allows you to define environment-specific variables. These are stored in src/environments/.

By default, youll find two files:

  • environment.ts For development
  • environment.prod.ts For production

Open environment.ts and add custom variables:

export const environment = {

production: false,

apiUrl: 'https://api.dev.example.com',

appVersion: '1.0.0'

};

In environment.prod.ts:

export const environment = {

production: true,

apiUrl: 'https://api.prod.example.com',

appVersion: '1.0.0'

};

Import and use these in your components or services:

import { environment } from '../../environments/environment';

console.log('API URL:', environment.apiUrl);

When you build your app with ng build --configuration production, Angular automatically replaces the environment variables with the production values.

Step 8: Build for Production

When your application is ready for deployment, generate optimized production builds using:

ng build

This creates a dist/ folder containing minified, bundled, and tree-shaken files ready for deployment to any static server (e.g., Netlify, Vercel, or AWS S3).

To optimize further for production, use:

ng build --configuration production --source-map

The --source-map flag generates source maps for easier debugging in production environments. The build process automatically enables:

  • Minification of JavaScript and CSS
  • Tree-shaking to remove unused code
  • AOT (Ahead-of-Time) compilation
  • Bundling with hashed filenames for caching

You can also specify a custom output path:

ng build --output-path=dist/my-app

Best Practices

Organize Your Project Structure Logically

As your application grows, a well-organized folder structure prevents chaos. Adopt a feature-based structure rather than a type-based one. Instead of grouping all components, services, and pipes in separate folders, group them by feature:

src/

??? app/

? ??? auth/

? ? ??? login/

? ? ? ??? login.component.ts

? ? ? ??? login.component.html

? ? ? ??? login.service.ts

? ? ??? register/

? ? ??? register.component.ts

? ? ??? register.component.html

? ??? dashboard/

? ? ??? dashboard.component.ts

? ? ??? dashboard.service.ts

? ? ??? dashboard-routing.module.ts

? ??? shared/

? ??? components/

? ??? directives/

? ??? pipes/

This structure makes it easier to locate, test, and reuse code related to a specific feature.

Use Standalone Components (Angular 14+)

Starting with Angular 14, standalone components allow you to create components without declaring them in a module. This simplifies the architecture and reduces boilerplate. To make a component standalone, add standalone: true to the @Component decorator:

@Component({

selector: 'app-hero-list',

standalone: true,

imports: [CommonModule],

templateUrl: './hero-list.component.html',

styleUrls: ['./hero-list.component.scss']

})

export class HeroListComponent { }

Standalone components are the future of Angular and are recommended for new projects.

Implement Consistent Coding Standards

Use ESLint and Prettier to enforce consistent code formatting and linting rules. Install them via:

npm install --save-dev eslint @typescript-eslint/parser @typescript-eslint/eslint-plugin prettier eslint-plugin-prettier

Create a .eslintrc.json and .prettierrc file in your project root to define your rules. Integrate them into your IDE for real-time feedback.

Use RxJS for State Management

For complex state management, avoid using simple variables in services. Instead, use RxJS BehaviorSubject or ReplaySubject to manage state as streams. For example:

import { BehaviorSubject } from 'rxjs';

export class HeroService {

private heroesSubject = new BehaviorSubject<string[]>([]);

public heroes$ = this.heroesSubject.asObservable();

loadHeroes() {

this.heroesSubject.next(['Iron Man', 'Captain America']);

}

}

Components can then subscribe to heroes$ using the async pipe in templates, eliminating manual subscription management.

Enable Strict TypeScript Settings

Open tsconfig.json and ensure the following strict settings are enabled:

{

"compilerOptions": {

"strict": true,

"noImplicitAny": true,

"noImplicitThis": true,

"strictNullChecks": true,

"strictFunctionTypes": true

}

}

These settings catch potential bugs at compile time, improving code reliability.

Write Unit and End-to-End Tests

Angular CLI automatically generates test files for components and services. Use Jasmine and Karma for unit tests, and Cypress or Protractor (deprecated) for E2E tests.

Run unit tests with:

ng test

Run E2E tests with:

ng e2e

Write tests early and often. Aim for at least 70% test coverage for critical components and services.

Use Lazy Loading for Routes

For large applications, lazy loading improves initial load time by loading feature modules only when needed. In app-routing.module.ts:

const routes: Routes = [

{ path: 'dashboard', loadChildren: () => import('./dashboard/dashboard.module').then(m => m.DashboardModule) },

{ path: 'auth', loadChildren: () => import('./auth/auth.module').then(m => m.AuthModule) }

];

With standalone components, lazy loading is achieved via loadComponent:

{ path: 'dashboard', loadComponent: () => import('./dashboard/dashboard.component').then(c => c.DashboardComponent) }

Tools and Resources

Essential Angular CLI Commands

Master these CLI commands to accelerate development:

  • ng generate component my-component Create a component
  • ng generate service my-service Create a service
  • ng generate module my-module Create a module
  • ng generate directive my-directive Create a directive
  • ng generate pipe my-pipe Create a pipe
  • ng serve Start dev server
  • ng build Build for production
  • ng test Run unit tests
  • ng lint Run ESLint
  • ng update Update Angular and dependencies

Recommended VS Code Extensions

Enhance your development experience with these extensions:

  • Angular Language Service Provides IntelliSense, error checking, and template navigation
  • ESLint Real-time linting for TypeScript and JavaScript
  • Prettier - Code formatter Auto-format code on save
  • Angular Snippets Quick code templates for common Angular patterns
  • Path Intellisense Auto-completes file paths in imports
  • GitLens Enhanced Git integration and blame annotations

Useful Online Resources

Performance Optimization Tools

Use these tools to analyze and optimize your app:

  • Angular DevTools Chrome extension for inspecting component trees, state, and change detection
  • Webpack Bundle Analyzer Visualize bundle sizes to identify large dependencies
  • Lighthouse Audit performance, accessibility, and SEO
  • Google PageSpeed Insights Get performance scores and recommendations

Real Examples

Example 1: Simple Todo App

Lets build a minimal Todo app to illustrate the setup process.

  1. Generate the project: ng new todo-app --routing --style=scss
  2. Create a Todo service: ng g s services/todo
  3. Define the Todo interface in models/todo.model.ts:
export interface Todo {

id: number;

text: string;

completed: boolean;

}

  1. Implement the service:
import { Injectable } from '@angular/core';

import { BehaviorSubject } from 'rxjs';

import { Todo } from '../models/todo.model';

@Injectable({

providedIn: 'root'

})

export class TodoService {

private todosSubject = new BehaviorSubject<Todo[]>([]);

public todos$ = this.todosSubject.asObservable();

addTodo(text: string) {

const newTodo: Todo = {

id: Date.now(),

text,

completed: false

};

const currentTodos = this.todosSubject.value;

this.todosSubject.next([...currentTodos, newTodo]);

}

toggleTodo(id: number) {

const currentTodos = this.todosSubject.value;

const updatedTodos = currentTodos.map(todo =>

todo.id === id ? { ...todo, completed: !todo.completed } : todo

);

this.todosSubject.next(updatedTodos);

}

}

  1. Generate a Todo component: ng g c todo-list
  2. Use the service in the component:
import { Component, OnInit } from '@angular/core';

import { TodoService, Todo } from '../services/todo.service';

@Component({

selector: 'app-todo-list',

templateUrl: './todo-list.component.html',

styleUrls: ['./todo-list.component.scss'],

standalone: true,

imports: [CommonModule]

})

export class TodoListComponent implements OnInit {

todos: Todo[] = [];

newTodoText = '';

constructor(private todoService: TodoService) { }

ngOnInit(): void {

this.todoService.todos$.subscribe(todos => this.todos = todos);

}

addTodo() {

if (this.newTodoText.trim()) {

this.todoService.addTodo(this.newTodoText);

this.newTodoText = '';

}

}

toggleTodo(id: number) {

this.todoService.toggleTodo(id);

}

}

  1. Render the list in the template:
<div class="todo-container">

<h2>My Todo List</h2>

<div class="input-group">

<input [(ngModel)]="newTodoText" placeholder="Add a new task" />

<button (click)="addTodo()">Add</button>

</div>

<ul>

<li *ngFor="let todo of todos" [class.completed]="todo.completed">

<input type="checkbox" (change)="toggleTodo(todo.id)" [checked]="todo.completed" />

<span>{{ todo.text }}</span>

</li>

</ul>

</div>

This example demonstrates core Angular concepts: components, services, RxJS, two-way binding, and standalone architectureall built from a clean setup.

Example 2: Enterprise Application with Feature Modules

In enterprise applications, teams often split features into separate modules for scalability. For example:

  • src/app/user/ Handles user profile, authentication, and settings
  • src/app/product/ Manages product catalog, search, and filters
  • src/app/order/ Manages cart, checkout, and history

Each feature folder contains its own components, services, models, and routing. This modular approach allows independent development, testing, and deployment of features by different teams.

Routing is configured lazily, so only the required module loads when a user navigates to its route. This significantly improves initial load performance.

FAQs

What is the difference between Angular and AngularJS?

AngularJS (version 1.x) is the original JavaScript framework released in 2010. Angular (versions 2+) is a complete rewrite using TypeScript, with a component-based architecture, improved performance, and mobile support. AngularJS is deprecated; all new projects should use Angular (v2+).

Do I need to install TypeScript separately?

No. TypeScript is bundled with the Angular CLI and configured automatically. You only need to install Node.js and the CLI.

Can I use Angular without the CLI?

Yes, but its not recommended. Manually configuring Webpack, Babel, and other tools is complex and error-prone. The CLI ensures best practices and reduces setup time.

How do I update Angular to a newer version?

Use the Angular Update Guide at https://update.angular.io. Run:

ng update @angular/core @angular/cli

The CLI will analyze your project and suggest safe updates.

Why is my build so slow?

Slow builds can result from large node_modules, unoptimized assets, or insufficient RAM. Use ng build --configuration production --source-map to analyze bundle sizes. Consider lazy loading and code splitting for large applications.

How do I deploy an Angular app?

Build your app with ng build --configuration production. Upload the contents of the dist/ folder to any static hosting service like Netlify, Vercel, GitHub Pages, or AWS S3.

Is Angular suitable for small projects?

Absolutely. Even small apps benefit from Angulars structure, testing capabilities, and tooling. The CLI makes setup quick, and standalone components reduce complexity.

What if I get a command not found error for ng?

This usually means the Angular CLI wasnt installed globally or the PATH is misconfigured. Reinstall with:

npm install -g @angular/cli

If using nvm, ensure youre on the correct Node version with nvm use.

Conclusion

Setting up an Angular project correctly is the foundation of building scalable, maintainable, and high-performing web applications. By following the steps outlined in this guidefrom installing prerequisites and generating a project with the CLI, to organizing code with best practices and leveraging powerful toolsyouve laid the groundwork for professional-grade development.

Angulars ecosystem, backed by Google and a massive open-source community, provides everything you need to build modern applications efficiently. Whether you're creating a simple dashboard or a complex enterprise platform, starting with a clean, well-structured project ensures long-term success.

Remember: the key to mastering Angular isnt just learning the syntaxits adopting its philosophy of modularity, reusability, and testability. Use the CLI to automate boilerplate, embrace standalone components, write tests early, and continuously optimize your builds.

Now that your project is set up, start building. Experiment with features, integrate APIs, and push your app to production. The journey of a thousand components begins with a single ng new command.