Skip to content

Project Structure and Configuration

📚 Reference Module: This module is your comprehensive guide to Angular project structure and configuration. While understanding the basic project layout is important, you don't need to memorize every configuration detail. Focus on the essentials (src/app/ folder, basic file structure) and bookmark this page as your configuration reference for when you need specific setup guidance.

Learning Approach for This Module

For beginners: Understand the basic project structure and where to put your code, then use this module as your go-to reference for configuration questions.

What to focus on now:

  • Basic project structure (src/app/ folder organization)
  • Where components, services, and assets go
  • Basic environment configuration concepts
  • File naming conventions

What to return to later:

  • Detailed angular.json configuration
  • Advanced TypeScript configuration
  • Build optimization settings
  • Complex asset management
  • Path mapping and advanced setups

Goal: Know where things go and how to organize your code. The detailed configuration comes naturally as you build more complex applications.

Angular Project Architecture

Understanding the structure of an Angular project is crucial for effective development. Let's explore each part of a typical Angular application.

Root Level Files

my-angular-app/
├── .angular/              # Angular CLI cache
├── .vscode/              # VS Code settings (optional)
├── node_modules/         # npm dependencies
├── src/                  # Source code
├── .editorconfig         # Editor configuration
├── .gitignore           # Git ignore rules
├── angular.json         # Angular CLI configuration
├── package.json         # npm configuration
├── package-lock.json    # npm lock file
├── README.md            # Project documentation
├── tsconfig.json        # TypeScript configuration
├── tsconfig.app.json    # App-specific TypeScript config
└── tsconfig.spec.json   # Test-specific TypeScript config

Key Configuration Files

📚 Reference Section: These configuration files control your Angular project. Focus on understanding what each file does, then return here when you need to modify specific settings.

package.json - Project Dependencies and Scripts

The heart of any Node.js project, containing metadata, dependencies, and npm scripts. You'll modify this when adding new packages or creating custom build scripts.

Common scenarios where you'll edit package.json:

  • Adding new dependencies (npm install package-name)
  • Creating custom build scripts for different environments
  • Updating Angular and other package versions
  • Adding development tools like linters or formatters
{
  "name": "my-angular-app",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "watch": "ng build --watch --configuration development",
    "test": "ng test"
  },
  "dependencies": {
    "@angular/animations": "^17.0.0",
    "@angular/common": "^17.0.0",
    "@angular/compiler": "^17.0.0",
    "@angular/core": "^17.0.0",
    "@angular/forms": "^17.0.0",
    "@angular/platform-browser": "^17.0.0",
    "@angular/platform-browser-dynamic": "^17.0.0",
    "@angular/router": "^17.0.0",
    "rxjs": "~7.8.0",
    "tslib": "^2.3.0",
    "zone.js": "~0.14.0"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "^17.0.0",
    "@angular/cli": "^17.0.0",
    "@angular/compiler-cli": "^17.0.0",
    "@types/jasmine": "~5.1.0",
    "jasmine-core": "~5.1.0",
    "karma": "~6.4.0",
    "karma-chrome-launcher": "~3.2.0",
    "karma-coverage": "~2.2.0",
    "karma-jasmine": "~5.1.0",
    "karma-jasmine-html-reporter": "~2.1.0",
    "typescript": "~5.2.0"
  }
}

angular.json - Angular CLI Configuration Hub

The central configuration file that controls how Angular CLI builds, serves, and tests your application. This file manages build configurations, asset inclusion, and optimization settings.

Key things you'll configure here:

  • Build output paths and optimization settings
  • Asset files (images, fonts, external stylesheets)
  • Development vs production configurations
  • Bundle budgets to control file sizes
  • Proxy settings for API calls during development
{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "my-angular-app": {
      "projectType": "application",
      "schematics": {
        "@schematics/angular:component": {
          "style": "css"
        }
      },
      "root": "",
      "sourceRoot": "src",
      "prefix": "app",
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist/my-angular-app",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": [
              "zone.js"
            ],
            "tsConfig": "tsconfig.app.json",
            "assets": [
              "public"
            ],
            "styles": [
              "src/styles.css"
            ],
            "scripts": []
          },
          "configurations": {
            "production": {
              "budgets": [
                {
                  "type": "initial",
                  "maximumWarning": "500kb",
                  "maximumError": "1mb"
                },
                {
                  "type": "anyComponentStyle",
                  "maximumWarning": "2kb",
                  "maximumError": "4kb"
                }
              ],
              "outputHashing": "all"
            },
            "development": {
              "buildOptimizer": false,
              "optimization": false,
              "vendorChunk": true,
              "extractLicenses": false,
              "sourceMap": true,
              "namedChunks": true
            }
          },
          "defaultConfiguration": "production"
        },
        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "configurations": {
            "production": {
              "buildTarget": "my-angular-app:build:production"
            },
            "development": {
              "buildTarget": "my-angular-app:build:development"
            }
          },
          "defaultConfiguration": "development"
        }
      }
    }
  }
}

tsconfig.json - TypeScript Compiler Settings

Controls how TypeScript compiles your Angular code. These settings affect type checking, module resolution, and build output.

Key configurations you might adjust:

  • strict: Enables strict type checking (recommended for new projects)
  • target: JavaScript version to compile to (ES2022 for modern browsers)
  • paths: Create import aliases for cleaner code organization
  • experimentalDecorators: Required for Angular's decorator syntax
{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "noImplicitOverride": true,
    "noPropertyAccessFromIndexSignature": true,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": true,
    "sourceMap": true,
    "declaration": false,
    "downlevelIteration": true,
    "experimentalDecorators": true,
    "moduleResolution": "node",
    "importHelpers": true,
    "target": "ES2022",
    "module": "ES2022",
    "useDefineForClassFields": false,
    "lib": [
      "ES2022",
      "dom"
    ]
  },
  "angularCompilerOptions": {
    "enableI18nLegacyMessageIdFormat": false,
    "strictInjectionParameters": true,
    "strictInputAccessModifiers": true,
    "strictTemplates": true
  }
}

Source Directory Structure

🎯 Focus Area: This is where you'll spend most of your time! Understand the src/app/ folder structure and file naming conventions - this knowledge will serve you daily.

/src Folder Overview - Your Development Workspace

The src folder contains all your application source code. This is where you'll build your Angular application.

Essential folders to understand:

  • app/ - Your main application code (components, services, etc.)

Files you'll work with regularly:

  • main.ts - Application startup (rarely modified)
  • index.html - Main HTML page (occasionally modified)
  • styles.css - Global application styles (frequently modified)

Static assets:

  • public/ - Static files (images, favicon, etc.) located at project root
  • Asset files are served directly from the public/ folder
src/
├── app/                  # Application code
│   ├── hello-world/      # Example feature component
│   │   ├── hello-world.ts      # Component TypeScript
│   │   ├── hello-world.html    # Component template
│   │   ├── hello-world.css     # Component styles
│   │   └── hello-world.spec.ts # Component tests
│   ├── app.ts            # Root component (Angular 20 standalone)
│   ├── app.html          # Root component template
│   ├── app.css           # Root component styles
│   ├── app.spec.ts       # Root component tests
│   ├── app.config.ts     # Application configuration
│   └── app.routes.ts     # Application routes
├── index.html            # Main HTML file
├── main.ts               # Application bootstrap
└── styles.css            # Global styles

Note: Angular 20 uses a simplified file structure:

  • No separate assets/ folder in src/ (static assets are in public/)
  • No environments/ folder by default (environment config is in app.config.ts)
  • No polyfills.ts (handled automatically by Angular CLI)
  • Component files use simple extensions (.ts, .html, .css) instead of .component.ts
  • favicon.ico is in the public/ folder at project root, not in src/

Key Application Files

src/main.ts

Application entry point:

import { bootstrapApplication } from '@angular/platform-browser';
import { appConfig } from './app/app.config';
import { App } from './app/app';

bootstrapApplication(App, appConfig)
  .catch((err) => console.error(err));

src/app/app.config.ts

Application configuration:

import { ApplicationConfig } from '@angular/core';
import { provideRouter } from '@angular/router';
import { provideHttpClient } from '@angular/common/http';

import { routes } from './app.routes';

export const appConfig: ApplicationConfig = {
  providers: [
    provideRouter(routes),
    provideHttpClient()
  ]
};

src/app/app.ts

Root component (Angular 20 standalone):

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

@Component({
  selector: 'app-root',
  imports: [RouterOutlet],
  templateUrl: './app.html',
  styleUrl: './app.css'
})
export class App {
  protected title = 'angular-demo-app';
}

title = 'my-angular-app'; }

#### `src/index.html`

Main HTML file:

```html
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>MyAngularApp</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
  <app-root></app-root>
</body>
</html>

Organizing Your Application

📚 Reference Section: These organization patterns become important as your application grows. Start simple and refactor to these patterns when you have multiple features.

Feature-Based Organization - Scaling Your Application

When to use this structure:

  • Applications with multiple distinct features
  • Teams working on different parts of the app
  • Need for clear separation of concerns
  • Planning for lazy loading

Benefits:

  • Clear feature boundaries
  • Easier code splitting and lazy loading
  • Better team collaboration
  • Simpler testing strategies
src/app/
├── core/                 # Singleton services, guards, interceptors
│   ├── services/
│   ├── guards/
│   └── interceptors/
├── shared/              # Reusable components, directives, pipes
│   ├── components/
│   ├── directives/
│   └── pipes/
├── features/            # Feature modules
│   ├── user-management/
│   │   ├── components/
│   │   ├── services/
│   │   └── user-management.module.ts
│   └── product-catalog/
│       ├── components/
│       ├── services/
│       └── product-catalog.module.ts
├── layout/              # Layout components
│   ├── header/
│   ├── footer/
│   └── sidebar/
└── app.component.ts

File Naming Conventions - Following Angular Standards

🎯 Essential Knowledge: These naming conventions are critical for Angular CLI and tooling to work properly. Follow these exactly - the CLI generates files with these patterns.

Why naming conventions matter:

  • Angular CLI relies on these patterns for code generation
  • IDEs and linters recognize these patterns for better tooling
  • Team consistency and code readability
  • Automated testing and build tool recognition

Angular follows specific naming conventions:

  • Components: my-component.component.ts
  • Services: my-service.service.ts
  • Modules: my-module.module.ts
  • Directives: my-directive.directive.ts
  • Pipes: my-pipe.pipe.ts
  • Guards: my-guard.guard.ts
  • Interfaces: my-interface.interface.ts
  • Models: my-model.model.ts

Real-world examples:

# Angular CLI automatically generates files with proper naming
ng generate component user-profile
# Creates: user-profile.component.ts, user-profile.component.html, etc.

ng generate service data-access
# Creates: data-access.service.ts

ng generate pipe currency-format
# Creates: currency-format.pipe.ts

Environment Configuration

📚 Reference Section: Environment configuration becomes crucial when deploying to different stages. Angular 20 uses a modern approach with configuration in app.config.ts and build-time replacements.

Modern Environment Configuration (Angular 20)

Angular 20 handles environment configuration through the application config and build-time replacements, rather than separate environment files.

Method 1: Configuration in app.config.ts

import { ApplicationConfig } from '@angular/core';
import { provideRouter } from '@angular/router';
import { provideHttpClient } from '@angular/common/http';
import { routes } from './app.routes';

// Environment-specific configuration
const isProduction = false; // Set by build process

export const appConfig: ApplicationConfig = {
  providers: [
    provideRouter(routes),
    provideHttpClient(),
    // Environment-specific providers
    ...(isProduction ? [] : [
      // Development-only providers
    ])
  ]
};

Method 2: Environment Files (Optional Legacy Approach)

If you prefer the traditional approach, you can still create environment files:

src/environments/environment.ts

export const environment = {
  production: false,
  apiUrl: 'http://localhost:3000/api',
  appName: 'My App (Dev)',
  enableLogging: true
};

src/environments/environment.prod.ts

export const environment = {
  production: true,
  apiUrl: 'https://api.myapp.com',
  appName: 'My App',
  enableLogging: false
};

Custom Environments - Beyond Development and Production

📚 Advanced Reference: Custom environments are useful for staging, testing, and CI/CD pipelines. Return to this when you need multiple deployment targets.

When you might need custom environments:

  • Staging environment that mirrors production
  • Testing environment with mock data
  • CI/CD environment with specific configurations
  • Demo environment for showcasing features

Modern Angular projects often use build-time environment variables and configuration providers:

// environment.staging.ts
export const environment = {
  production: false,
  apiUrl: 'https://staging-api.myapp.com',
  appName: 'My App (Staging)',
  enableLogging: true,
  featureFlags: {
    enableNewUI: true,
    enableBetaFeatures: true
  }
};

Update angular.json to include staging configuration:

"configurations": {
  "production": {
    "fileReplacements": [
      {
        "replace": "src/environments/environment.ts",
        "with": "src/environments/environment.prod.ts"
      }
    ]
  },
  "staging": {
    "fileReplacements": [
      {
        "replace": "src/environments/environment.ts",
        "with": "src/environments/environment.staging.ts"
      }
    ]
  }
}

Build for staging:

ng build --configuration staging

Asset Management

🎯 Essential Knowledge: Asset management is fundamental for images, icons, and static files. Learn the basics here and return for optimization strategies.

Static Assets - Organizing Your Project Resources

Best practices for asset organization:

  • Use descriptive folder names (images/, icons/, data/)
  • Optimize images before adding them to assets
  • Consider using CDNs for large media files
  • Keep asset sizes reasonable for web performance

Asset optimization tips:

  • Compress images (use tools like ImageOptim, TinyPNG)
  • Use SVG for icons when possible
  • Consider WebP format for better compression
  • Implement lazy loading for large images

Place static files in the public/ folder (Angular 20 approach):

public/
├── images/
│   ├── logo.png
│   └── background.jpg
├── icons/
│   ├── user.svg
│   └── settings.svg
├── data/
│   └── config.json
├── styles/
│   └── themes.css
└── favicon.ico

Note: In Angular 20, static assets are placed in the public/ folder at the project root, not in src/assets/. Files in public/ are served directly and can be referenced without the assets/ prefix.

Referencing Assets - Using Static Files in Your Application

Asset referencing patterns (Angular 20):

  • Template references: Direct path from public/ folder
  • CSS references: Direct path from public/ folder
  • TypeScript references: Direct path strings

In templates:

<img src="images/logo.png" alt="Logo">
<img src="icons/user.svg" alt="User">

In CSS:

.background {
  background-image: url('images/background.jpg');
}

In TypeScript:

const configUrl = 'data/config.json';

Note: With the public/ folder approach, assets are served directly from the root path without needing an assets/ prefix.

Global Styles - Application-Wide Styling

🎯 Essential Knowledge: Global styles affect your entire application. Understand how to include external libraries and create consistent styling.

src/styles.css - Your Global Stylesheet

Common global style patterns:

  • CSS resets and normalize styles
  • Typography and color system setup
  • Utility classes for common layouts
  • Third-party library imports
/* Global styles */
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  font-family: 'Roboto', sans-serif;
  line-height: 1.6;
  color: #333;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

Include external stylesheets in angular.json:

"styles": [
  "node_modules/bootstrap/dist/css/bootstrap.min.css",
  "src/styles.css"
]

Build Configuration

📚 Reference Section: Build configuration controls how your application is optimized for different environments. Focus on understanding the differences between development and production builds initially.

Development Build - Fast Development Iteration

Development build characteristics:

  • Fast compilation for quick feedback during development
  • Source maps for debugging TypeScript in browser dev tools
  • No minification for readable code in browser
  • Hot module replacement for instant updates
ng build --configuration development

Features:

  • Source maps enabled
  • No optimization
  • Larger bundle size
  • Faster build time

Production Build - Optimized for Deployment

Production build optimizations:

  • Minification reduces file sizes significantly
  • Tree-shaking eliminates unused code
  • Ahead-of-Time (AOT) compilation catches errors early
  • Bundle splitting improves loading performance
ng build --configuration production

Features:

  • Minified and optimized code
  • Tree-shaking (removes unused code)
  • Ahead-of-Time (AOT) compilation
  • Bundle splitting
  • Compression

Build Optimization - Performance and Size Control

📚 Advanced Reference: These optimization techniques become important as your application grows. Return here when you need to improve performance or reduce bundle size.

Bundle Budgets - Controlling Application Size

Why bundle budgets matter:

  • Prevent applications from becoming too large
  • Maintain good user experience on slower networks
  • Early warning system for performance issues
  • Automatic CI/CD integration for size monitoring

Control bundle sizes in angular.json:

"budgets": [
  {
    "type": "initial",
    "maximumWarning": "500kb",
    "maximumError": "1mb"
  },
  {
    "type": "anyComponentStyle",
    "maximumWarning": "2kb",
    "maximumError": "4kb"
  }
]

Performance Tips - Advanced Optimization Strategies

When to implement these optimizations:

  • Application loading feels slow
  • Bundle sizes exceed budget warnings
  • Poor Lighthouse performance scores
  • User feedback about loading times

  • Lazy Loading: Load modules on demand

  • OnPush Change Detection: Optimize component updates
  • Tree Shaking: Remove unused imports
  • Code Splitting: Break code into chunks
  • Service Workers: Cache resources

Development Tools Configuration

📚 Reference Section: These configuration files improve your development experience. Set up once and refer back when adding new tools or team members.

VS Code Settings - Optimizing Your Development Environment

Benefits of proper VS Code configuration:

  • Consistent formatting across team members
  • Automatic import organization
  • Better TypeScript and Angular support
  • Faster development with proper autocomplete

Create .vscode/settings.json:

{
  "typescript.preferences.importModuleSpecifier": "relative",
  "typescript.suggest.autoImports": true,
  "editor.formatOnSave": true,
  "editor.codeActionsOnSave": {
    "source.organizeImports": true
  },
  "files.associations": {
    "*.html": "html"
  },
  "emmet.includeLanguages": {
    "typescript": "html"
  }
}

Core Angular development extensions:

  • Angular Language Service: Template syntax highlighting and autocomplete
  • TypeScript Hero: Import management and code organization
  • Prettier: Consistent code formatting
  • ESLint: Code quality and error detection

Create .vscode/extensions.json:

{
  "recommendations": [
    "angular.ng-template",
    "ms-vscode.vscode-typescript-next",
    "bradlc.vscode-tailwindcss",
    "esbenp.prettier-vscode",
    "ms-vscode.vscode-eslint"
  ]
}

Path Mapping

📚 Reference Section: Path mapping creates cleaner import statements and better code organization. Implement this when your application has deep folder structures.

TypeScript Path Mapping - Cleaner Import Statements

Benefits of path mapping:

  • Eliminates complex relative imports (../../../)
  • Makes refactoring easier
  • Improves code readability
  • Consistent import paths across the project

When to set up path mapping:

  • Deep folder structures making imports complex
  • Frequently importing from core/shared folders
  • Team members struggling with relative import paths
  • Preparing for larger application structure

Update tsconfig.json for cleaner imports:

{
  "compilerOptions": {
    "baseUrl": "./",
    "paths": {
      "@app/*": ["src/app/*"],
      "@shared/*": ["src/app/shared/*"],
      "@core/*": ["src/app/core/*"],
      "@components/*": ["src/app/components/*"],
      "@services/*": ["src/app/services/*"]
    }
  }
}

Usage comparison:

// Instead of complex relative imports
import { UserService } from '../../core/services/user.service';
import { SharedComponent } from '../../../shared/components/shared.component';

// Use clean alias imports
import { UserService } from '@core/services/user.service';
import { SharedComponent } from '@shared/components/shared.component';

Summary

📚 Quick Reference Card: Bookmark this section for quick lookups during development.

Understanding Angular project structure helps you:

  • Navigate projects efficiently
  • Follow Angular conventions
  • Organize code effectively
  • Configure builds properly
  • Manage assets and environments
  • Set up development tools

Essential knowledge for daily development:

  • src/app/ folder organization and file placement
  • Asset references and global styling
  • Environment variable usage
  • File naming conventions

Reference knowledge to return to:

  • Advanced angular.json configuration
  • Build optimization and bundle budgets
  • Development tools setup
  • Path mapping for complex projects

Key takeaways:

  • angular.json controls CLI behavior and build processes
  • src/app/ contains your application code
  • Environment files manage configuration across deployments
  • Asset organization improves maintainability
  • Proper structure scales with project growth
  • Development tools configuration improves team productivity

Next Steps

Now that you understand project structure, you're ready to:

  1. Create your first Angular component - Learn the building blocks
  2. Understand dependency injection - How Angular provides services
  3. Explore data binding and templates - Connect data to your UI
  4. Learn about routing - Navigate between different views

Recommended learning path:

  • Focus on basic component creation first
  • Practice with simple file organization
  • Return to advanced configuration as your projects grow
  • Implement optimization strategies for production applications

The foundation is set for building robust Angular applications!