Setup and Installation
Prerequisites
Section titled “Prerequisites”Before you start, ensure you have the following installed:
- Node.js (v18.19 or higher)
- npm (v9 or higher) or yarn
- A code editor (VS Code recommended)
- Basic knowledge of TypeScript and JavaScript
Step 1: Install Node.js
Section titled “Step 1: Install Node.js”Visit nodejs.org and download the LTS (Long-Term Support) version.
After installation, verify:
node --version # Should be v18.19.0 or highernpm --version # Should be v9.0.0 or higherStep 2: Install Angular CLI
Section titled “Step 2: Install Angular CLI”The Angular CLI is the official command-line tool for creating and managing Angular projects.
npm install -g @angular/cli@latestVerify the installation:
ng versionYou should see output similar to:
_ _ ____ _ ___ / \ _ __ __ _ _ _| | __ _ _ __ / ___| | |_ _| / △ \ | '_ \ / _` | | | | |/ _` | '__| | | | | | | / ___ \ | | | | (_| | | | | | (_| | | | |___| |___ | | /_/ \_\|_| |_|\__, |_|_|_|_|\__,_|_| \____|_____|___| |___/Angular CLI: 18.0.0Node: 18.19.0Package Manager: npm 10.2.3Step 3: Create a New Angular Project
Section titled “Step 3: Create a New Angular Project”The Angular CLI provides an interactive setup for creating new projects:
ng new my-appThe CLI will prompt you with several questions:
? Which stylesheet format would you like to use?> CSS SCSS (recommended for large projects) SASS LESS
? Do you want to enable Server-Side Rendering (SSR)?> Yes No (recommended for most projects)
? Do you want to add Angular routing?> Yes (recommended) Nong new my-app --skip-git --package-manager=npmProject Structure
Section titled “Project Structure”After creation, your project will look like:
my-app/├── src/│ ├── app/│ │ ├── app.component.ts│ │ ├── app.component.html│ │ ├── app.component.scss│ │ ├── app.component.spec.ts│ │ └── app.routes.ts│ ├── main.ts # Application entry point│ ├── styles.scss # Global styles│ └── index.html # HTML template├── angular.json # Angular CLI configuration├── tsconfig.json # TypeScript configuration├── package.json # Dependencies└── README.mdStep 4: Navigate to Project Directory
Section titled “Step 4: Navigate to Project Directory”cd my-appStep 5: Start the Development Server
Section titled “Step 5: Start the Development Server”ng serveOr with automatic browser opening:
ng serve --openThe application will be available at http://localhost:4200/
Understanding the Development Server Output
Section titled “Understanding the Development Server Output”✔ Browser application bundle generation complete.
Initial Chunk Files | Names | Raw Size | Estimated Gzipmain.js | main | 234 kB | 68 kBpolyfills.js | polyfills | 124 kB | 39 kBstyles.css | styles | 25 kB | 6 kB
Build at: 2024-05-11T10:30:45.123Z - Hash: abc123def456
Application bundle generation complete. [4.234 seconds]
Watch mode enabled. Watching for file changes...Step 6: Edit Your First Component
Section titled “Step 6: Edit Your First Component”Open src/app/app.component.ts:
import { Component } from '@angular/core';
@Component({ selector: 'app-root', standalone: true, template: ` <h1>Welcome to {{ title }}!</h1> `, styles: [],})export class AppComponent { title = 'my-app';}Edit the template to see changes instantly:
template: ` <h1>Hello, Angular 18!</h1> <p>Welcome to your first Angular application</p>`Save the file and watch the browser reload automatically.
Common Setup Options
Section titled “Common Setup Options”With SCSS (Recommended for Large Projects)
Section titled “With SCSS (Recommended for Large Projects)”ng new my-app --style=scssWith Routing Enabled
Section titled “With Routing Enabled”ng new my-app --routingWithout Angular CLI Prompts
Section titled “Without Angular CLI Prompts”ng new my-app \ --skip-git \ --style=scss \ --routing \ --package-manager=npmSkip Installation (Install Later)
Section titled “Skip Installation (Install Later)”ng new my-app --skip-installcd my-appnpm installDevelopment Commands
Section titled “Development Commands”Once your project is created, you have several useful commands:
# Start development serverng serve
# With auto-open browserng serve --open
# On specific portng serve --port 4300# Production build (optimized)ng build
# Development buildng build --configuration development
# Build for specific environmentng build --configuration staging# Run unit testsng test
# With coverageng test --code-coverage
# Run E2E testsng e2e# Generate componentng generate component components/button
# Generate serviceng generate service services/api
# Generate directiveng generate directive directives/highlight
# Short syntaxng g c my-componentng g s my-serviceng g d my-directiveVS Code Extensions (Recommended)
Section titled “VS Code Extensions (Recommended)”For a better development experience in VS Code:
- Angular Language Service — Official extension by Angular
- Prettier — Code formatter
- ESLint — Linting support
- TypeScript Vue Plugin (Volar) — Better TypeScript support
Install them via the Extensions marketplace.
Environment Configuration
Section titled “Environment Configuration”Angular supports multiple environments. Edit angular.json to add configurations:
"configurations": { "development": { "budgets": [...], "namedChunks": true }, "production": { "budgets": [...], "aot": true, "outputHashing": "all" }, "staging": { "budgets": [...], "aot": true }}Build for different environments:
ng build --configuration productionng build --configuration stagingManaging Multiple Node Versions with NVM
Section titled “Managing Multiple Node Versions with NVM”If you work on multiple projects with different Node.js version requirements, NVM (Node Version Manager) allows you to easily switch between versions.
Installing NVM
Section titled “Installing NVM”macOS and Linux
Section titled “macOS and Linux”curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bashAfter installation, close and reopen your terminal, then verify:
nvm --version # Should display version numberWindows
Section titled “Windows”Use nvm-windows from: https://github.com/coreybutler/nvm-windows/releases
Download the installer and follow the installation instructions.
Managing Node Versions with NVM
Section titled “Managing Node Versions with NVM”List Available Node Versions
Section titled “List Available Node Versions”nvm list-remote # Show all available versionsInstall a Specific Node Version
Section titled “Install a Specific Node Version”nvm install 18.19.0 # Install specific versionnvm install 20.11.0 # Install another versionnvm install --lts # Install latest LTS versionList Installed Versions
Section titled “List Installed Versions”nvm list # or `nvm ls`Output example:
v16.13.0 v18.19.0-> v20.11.0 (current) v21.5.0Switch Node Versions
Section titled “Switch Node Versions”nvm use 18.19.0 # Use specific version for current terminal sessionnvm use --lts # Use latest LTS versionSet Default Node Version
Section titled “Set Default Node Version”nvm alias default 18.19.0Use Project-Specific Versions
Section titled “Use Project-Specific Versions”Create a .nvmrc file in your project root:
18.19.0Then automatically use the correct version:
nvm use # Reads .nvmrc and switches to specified versionExample: Managing Multiple Projects
Section titled “Example: Managing Multiple Projects”# Project 1 (Angular 18 - needs Node 18)cd my-angular-appnvm use 18.19.0ng serve
# Project 2 (Node backend - needs Node 20)cd ../my-apinvm use 20.11.0npm startTroubleshooting Common Setup Issues
Section titled “Troubleshooting Common Setup Issues”Issue: ng: command not found
Section titled “Issue: ng: command not found”Symptoms:
bash: ng: command not foundCauses:
- Angular CLI not installed globally
- npm global bin directory not in PATH
- Installation failed silently
Solutions:
- Install Angular CLI globally:
npm install -g @angular/cli@latest- Verify npm global directory:
npm config get prefix- If using nvm, reinstall global packages after switching versions:
npm install -g @angular/cli@latest- Use npx instead (no global installation needed):
npx @angular/cli@latest servenpx @angular/cli@latest generate component my-componentIssue: Port 4200 Already in Use
Section titled “Issue: Port 4200 Already in Use”Symptoms:
Error: Port 4200 is already in use. Would you like to use a different port (4201)?Causes:
- Another application using the port
- Previous Angular server still running
- Multiple development servers started
Solutions:
- Use a different port:
ng serve --port 4300- Kill the process using port 4200:
macOS/Linux:
lsof -ti:4200 | xargs kill -9Windows (PowerShell):
Stop-Process -Id (Get-NetTCPConnection -LocalPort 4200).OwningProcess -Force- Check what’s using the port:
macOS/Linux:
lsof -i :4200Windows (Command Prompt):
netstat -ano | findstr :4200Issue: Node Version Not Compatible
Section titled “Issue: Node Version Not Compatible”Symptoms:
The engine "node" is incompatible with this module.Expected version ">=18.19.0". Got "16.13.0"Causes:
- Node.js version too old
- Project requires specific Node version
- Version mismatch between projects
Solutions:
- Check current Node version:
node --version-
Update Node.js directly:
- Visit nodejs.org and download the LTS version
- Run the installer
-
Use NVM for version management (Recommended):
nvm install 18.19.0nvm use 18.19.0node --version # Verify the change- Create
.nvmrcin project root:
18.19.0Then use:
nvm useIssue: npm install Hangs or Fails
Section titled “Issue: npm install Hangs or Fails”Symptoms:
npm ERR! code ERESOLVEnpm ERR! ERESOLVE unable to resolve dependency treeCauses:
- Corrupted npm cache
- Conflicting dependencies
- Network issues
- npm configuration issues
Solutions:
- Clear npm cache:
npm cache clean --forcenpm install- Try npm install with legacy peer deps:
npm install --legacy-peer-deps- Delete lock file and reinstall:
rm package-lock.jsonnpm install- Use npm ci (Recommended for clean installs):
npm ci # Installs exact versions from package-lock.json- Update npm itself:
npm install -g npm@latestIssue: TypeScript Compilation Errors
Section titled “Issue: TypeScript Compilation Errors”Symptoms:
error TS2304: Cannot find name 'NgModule'error TS1005: ',' expectedCauses:
- TypeScript version mismatch
- Missing type definitions
- Incorrect tsconfig.json
- Angular packages not installed
Solutions:
- Reinstall Angular dependencies:
rm node_modules package-lock.jsonnpm install- Update Angular and related packages:
ng update @angular/core @angular/cli- Check TypeScript version:
npx tsc --version- Rebuild the project:
ng buildIssue: CORS Errors When Fetching Data
Section titled “Issue: CORS Errors When Fetching Data”Symptoms:
Access to XMLHttpRequest at 'http://api.example.com/data'from origin 'http://localhost:4200' has been blocked by CORS policyCauses:
- Backend API doesn’t allow requests from localhost:4200
- Missing CORS headers on backend
- Incorrect proxy configuration
Solutions:
- Use proxy configuration in development:
Create/edit proxy.conf.json:
{ "/api": { "target": "http://localhost:3000", "secure": false, "pathRewrite": { "^/api": "" } }}- Update
angular.json:
"serve": { "options": { "proxyConfig": "proxy.conf.json" }}- Use the proxy in your API calls:
// Instead of: http://localhost:3000/api/usersthis.http.get('/api/users')Issue: Memory Errors During Build
Section titled “Issue: Memory Errors During Build”Symptoms:
JavaScript heap out of memoryFATAL ERROR: CALL_AND_RETRY_LAST Allocation failedCauses:
- Large project with many dependencies
- Default Node memory limit too low
- Inefficient build configuration
Solutions:
- Increase Node memory:
export NODE_OPTIONS=--max_old_space_size=4096ng build- For Windows (Command Prompt):
set NODE_OPTIONS=--max_old_space_size=4096ng build- For Windows (PowerShell):
$env:NODE_OPTIONS="--max_old_space_size=4096"ng build- Add to npm scripts in
package.json:
{ "scripts": { "build": "export NODE_OPTIONS=--max_old_space_size=4096 && ng build" }}Issue: Module Not Found Errors
Section titled “Issue: Module Not Found Errors”Symptoms:
error TS2307: Cannot find module '@angular/core' or its corresponding type declarationsCauses:
- Missing node_modules directory
- Incomplete npm installation
- Package.json missing dependencies
- Incorrect import paths
Solutions:
- Reinstall dependencies:
npm install- Check if package is in package.json:
grep "@angular/core" package.json- Install missing packages:
npm install @angular/core --save- Verify import paths use correct aliases:
// Goodimport { MyComponent } from '@app/components/my-component';
// Bad (if path alias not configured)import { MyComponent } from '../../../components/my-component';Issue: Port Already in Use (Extended)
Section titled “Issue: Port Already in Use (Extended)”Find and kill processes by port (All platforms):
# Use this npm package (works everywhere)npm install -g kill-portkill-port 4200Or create a utility script in package.json:
{ "scripts": { "kill:4200": "kill-port 4200", "serve": "npm run kill:4200 && ng serve" }}Debugging Setup Issues
Section titled “Debugging Setup Issues”Enable Verbose Logging
Section titled “Enable Verbose Logging”ng serve --verboseThis provides detailed information about the build process and can help identify issues.
Check System Information
Section titled “Check System Information”ng version --verboseShows detailed Angular and system information useful for debugging.
Common Environment Variables
Section titled “Common Environment Variables”# Skip package manager installationng new my-app --skip-install
# Use specific package managerng new my-app --package-manager=npm
# Skip git initializationng new my-app --skip-git
# Use specific Angular versionng new my-app --package-manager npm --version 17Next Steps
Section titled “Next Steps”Once your development environment is set up:
- ✅ Create your first component
- ✅ Understand Angular’s component architecture
- ✅ Learn about services and dependency injection
- ✅ Explore routing and navigation
- ✅ Master forms and form validation
- ✅ Add HTTP communication with your backend