Understanding the Angular CLI¶
📚 Reference Module: This module serves as a comprehensive reference guide to the Angular CLI. While it's good to know these commands exist, you don't need to memorize them all right now. Focus on the basics (
ng new,ng serve,ng generate component) and return to this module when you need specific functionality during your Angular development journey.
What is the Angular CLI?¶
The Angular Command Line Interface (CLI) is a powerful tool that helps you create, develop, scaffold, and maintain Angular applications. It provides a consistent development experience and automates many common tasks.
Learning Approach for This Module¶
For beginners: Read through the "Essential Commands" section to understand the basics, then bookmark this page as your CLI reference. You'll naturally learn more commands as you build projects.
What to focus on now:
ng new- Creating projectsng serve- Running the development serverng generate component- Creating componentsng build- Building for production
What to return to later:
- Advanced generation options
- Build optimization
- Testing commands
- Workspace management
- Troubleshooting guides
The goal is to know these tools exist so you can find them when needed, not to master everything immediately.
Key Features¶
- Project Creation: Scaffold new Angular projects with best practices
- Code Generation: Generate components, services, modules, and more
- Development Server: Hot-reload development server
- Building: Build applications for production
- Testing: Run unit tests and end-to-end tests
- Linting: Code quality checks
- Updates: Keep your project dependencies up to date
Essential Commands¶
Project Management¶
These commands help you manage the lifecycle of your Angular project, from creation to deployment. Each command serves a specific purpose in your development workflow:
- ng new: Sets up a complete project structure with all necessary configuration files
- ng serve: Starts a local development server with hot-reload for rapid development
- ng build: Compiles your application into optimized files ready for deployment
Understanding when and why to use each command is crucial for effective Angular development.
# Create a new Angular workspace and initial app
ng new my-app
# Generate a new Angular app within workspace (for multi-app workspaces)
ng generate application my-app
# Serve the app on development server (hot-reload enabled)
ng serve
# Build the app for production (optimized, minified)
ng build
# Build and watch for changes (useful during development)
ng build --watch
Code Generation (Schematics)¶
Angular CLI schematics are templates that generate code following Angular best practices and conventions. They ensure consistency across your project and save time by automatically creating the boilerplate code you need.
What are schematics? Think of them as intelligent code templates that not only create files but also:
- Follow Angular naming conventions automatically
- Add proper imports and dependencies
- Update module declarations when needed
- Create accompanying test files
- Apply your project's configured styling preferences
This automation prevents common mistakes and ensures all developers on your team follow the same patterns.
# Generate a component
ng generate component my-component
ng g c my-component # shorthand
# Generate a service
ng generate service my-service
ng g s my-service # shorthand
# Generate a module
ng generate module my-module
ng g m my-module # shorthand
# Generate a directive
ng generate directive my-directive
ng g d my-directive # shorthand
# Generate a pipe
ng generate pipe my-pipe
ng g p my-pipe # shorthand
# Generate a guard
ng generate guard my-guard
ng g g my-guard # shorthand
# Generate an interface
ng generate interface my-interface
ng g i my-interface # shorthand
# Generate an enum
ng generate enum my-enum
ng g e my-enum # shorthand
Advanced Generation Options¶
These advanced options give you fine-grained control over how Angular CLI generates your code. Understanding these options helps you customize the generated files to match your project structure and preferences.
Key concepts:
- --skip-tests: Useful when you prefer to write tests separately or use different testing strategies
- --inline-style/--inline-template: Keeps styles and templates in the same file as the component (good for small components)
- --module: Specifies which module should import the new component (essential for feature modules)
- --routing: Automatically sets up routing configuration for modules
# Generate component with specific options
ng g c my-component --skip-tests --inline-style --inline-template
# Generate component in specific module
ng g c components/my-component --module=app
# Generate service with specific options
ng g s services/my-service --skip-tests
# Generate module with routing
ng g m features/my-feature --routing
# Generate lazy-loaded module
ng g m features/lazy-feature --route lazy --module app
Angular CLI Configuration¶
Global Configuration¶
View global configuration:
Set global defaults:
# Set default style extension
ng config -g defaults.styleExt scss
# Set default component generation options
ng config -g defaults.component.inlineStyle true
ng config -g defaults.component.spec false
# Set default application shell options
ng config -g defaults.build.sourceMap false
Project Configuration¶
The angular.json file contains project-specific configuration.
In Angular 20, this structure has been updated to use the new application builder and simplified asset handling.
Key changes in Angular 20:
- Uses
@angular/build:applicationbuilder instead of the older browser builder - Assets are now configured with
globpatterns from thepublic/folder - Bundle budgets help you monitor application size
- Separate development and production configurations optimize for different environments
{
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
"version": 1,
"newProjectRoot": "projects",
"projects": {
"my-app": {
"projectType": "application",
"schematics": {
"@schematics/angular:component": {
"style": "css",
"skipTests": false
}
},
"root": "",
"sourceRoot": "src",
"prefix": "app",
"architect": {
"build": {
"builder": "@angular/build:application",
"options": {
"browser": "src/main.ts",
"polyfills": ["zone.js"],
"tsConfig": "tsconfig.app.json",
"assets": [
{
"glob": "**/*",
"input": "public"
}
],
"styles": ["src/styles.css"]
},
"configurations": {
"production": {
"budgets": [
{
"type": "initial",
"maximumWarning": "500kB",
"maximumError": "1MB"
}
],
"outputHashing": "all"
},
"development": {
"optimization": false,
"extractLicenses": false,
"sourceMap": true
}
}
}
}
}
}
}
Development Server Options¶
The Angular development server is built on top of Webpack's dev server and provides hot-reload functionality, meaning your browser automatically refreshes when you make changes to your code. Understanding these options helps you customize your development environment for different scenarios.
Basic Serving¶
These are the most commonly used serving options for day-to-day development:
# Default serving (port 4200)
ng serve
# Serve on specific port (useful when port 4200 is busy)
ng serve --port 4300
# Open browser automatically (saves time during development)
ng serve --open
# Serve with HTTPS (required for testing PWA features, geolocation, etc.)
ng serve --ssl
# Serve with custom host (allows access from other devices on your network)
ng serve --host 0.0.0.0
Advanced Serving Options¶
These options are useful for specific development scenarios and troubleshooting:
# Enable polling for file changes (useful in Docker or virtual machines)
ng serve --poll 2000
# Disable host checking (use carefully, only for development)
ng serve --disable-host-check
# Serve with proxy configuration (redirect API calls during development)
ng serve --proxy-config proxy.conf.json
# Serve specific configuration (test production settings locally)
ng serve --configuration production
Proxy Configuration¶
During development, you often need to call APIs that run on different ports or servers. The proxy configuration helps you avoid CORS issues by redirecting API calls through the Angular dev server.
Create proxy.conf.json for API proxying:
{
"/api/*": {
"target": "http://localhost:3000",
"secure": true,
"changeOrigin": true,
"logLevel": "debug"
}
}
What this does: When your Angular app makes a request to /api/users, it gets redirected to http://localhost:3000/api/users,
solving CORS issues during development.
Building Applications¶
The Angular CLI build system uses Webpack under the hood to bundle, optimize, and transform your TypeScript code into optimized JavaScript that browsers can understand. The build process handles:
- TypeScript compilation - Converts your TypeScript code to JavaScript
- Bundle optimization - Combines multiple files into fewer, optimized chunks
- Tree shaking - Removes unused code to reduce bundle size
- Asset processing - Handles CSS, images, and other static assets
- Code splitting - Creates separate bundles for better loading performance
Understanding different build configurations helps you optimize your application for development speed versus production performance.
Development Build¶
The development build prioritizes fast compilation and debugging capabilities over optimization:
What happens during development build:
- Source maps are generated for easier debugging
- Code is not minified (human-readable)
- Faster compilation with fewer optimizations
- Larger bundle sizes but quicker build times
Production Build¶
The production build focuses on optimization and performance for end users:
What happens during production build:
- Code minification and uglification
- Dead code elimination (tree shaking)
- Ahead-of-Time (AOT) compilation
- Bundle optimization and compression
- Source maps disabled by default (smaller size)
Note: The
--prodflag is deprecated in newer Angular versions. Always use--configuration production.
Build Options¶
These options give you fine-grained control over the build process:
# Build with source maps (helpful for debugging production issues)
ng build --source-map
# Build with specific output path (useful for CI/CD pipelines)
ng build --output-path dist/my-custom-folder
# Build with base href (required when deploying to subdirectories)
ng build --base-href /my-app/
# Build and watch for changes (continuous development)
ng build --watch
# Build with bundle analysis (understand what's in your bundles)
ng build --stats-json
Key Build Options Explained:
- Source Maps (
--source-map): Create .map files that help browsers show original TypeScript code in debugger instead of compiled JavaScript - Output Path (
--output-path): Specify where build files are placed - useful for custom deployment setups - Base Href (
--base-href): Sets the base URL for your app - essential when deploying to subdirectories likeexample.com/my-app/ - Watch Mode (
--watch): Automatically rebuilds when files change - faster than full rebuilds during development - Stats JSON (
--stats-json): Generates detailed bundle analysis data for tools like webpack-bundle-analyzer
Environment Configuration¶
Angular supports multiple environments (development, staging, production) through configuration files:
# Build for specific environment
ng build --configuration staging
# Build for production with custom config
ng build --configuration production,fr
Environment configurations are defined in angular.json and can include:
- Different API endpoints for dev/staging/prod
- Feature flags for different environments
- Different optimization settings
- Locale-specific builds for internationalization
Example use cases:
stagingenvironment with production optimizations but pointing to test APIsproduction,frconfiguration that builds for production with French localizationdevelopmentwith debug tools enabled and local API endpoints
Testing Commands¶
Angular CLI provides comprehensive testing capabilities built on Jasmine (testing framework) and Karma (test runner). Testing is essential for maintaining code quality, catching bugs early, and ensuring your application works as expected.
Unit Testing¶
Unit tests verify individual components, services, and functions in isolation. Angular uses Jasmine for writing tests and Karma for running them in real browsers.
# Run unit tests
ng test
# Run tests in watch mode (default)
ng test --watch
# Run tests once
ng test --watch=false
# Run tests with code coverage
ng test --code-coverage
# Run tests on specific browsers
ng test --browsers Chrome,Firefox
Key Testing Concepts:
- Watch Mode: Automatically re-runs tests when files change - great for Test-Driven Development (TDD)
- Code Coverage: Shows what percentage of your code is tested - helps identify untested areas
- Browser Testing: Tests run in real browsers to catch browser-specific issues
- Headless Testing: Use
--browsers=ChromeHeadlessfor CI/CD environments without GUI
Common Testing Scenarios:
# Continuous testing during development
ng test --watch
# One-time test run for CI/CD
ng test --watch=false --browsers=ChromeHeadless
# Generate coverage report
ng test --code-coverage --watch=false
# Test with specific configuration
ng test --configuration=ci
End-to-End Testing¶
E2E tests verify complete user workflows by simulating real user interactions. Modern Angular projects use Cypress or Playwright instead of the deprecated Protractor.
Note: E2E testing setup depends on your chosen framework (Cypress, Playwright, etc.) and may require additional configuration.
Code Quality and Analysis¶
Code quality tools help maintain consistent coding standards, catch potential issues, and improve code maintainability. Angular CLI integrates with popular linting and analysis tools.
Linting¶
Linting analyzes your code for potential errors, coding standard violations, and suspicious patterns. Modern Angular projects typically use ESLint (replacing the deprecated TSLint).
# Lint TypeScript files
ng lint
# Lint and fix automatically fixable issues
ng lint --fix
# Lint specific files
ng lint --files src/app/my-component.ts
What linting catches:
- TypeScript compilation errors
- Code style violations (spacing, naming conventions)
- Potential runtime errors (unused variables, unreachable code)
- Angular-specific best practices
- Accessibility issues (with appropriate rules)
Setting up ESLint for new projects:
Bundle Analysis¶
Understanding your application's bundle size and composition is crucial for performance optimization. Bundle analysis helps identify large dependencies and optimization opportunities.
# Generate bundle stats
ng build --stats-json
# Analyze bundle with webpack-bundle-analyzer
npx webpack-bundle-analyzer dist/my-app/stats.json
Bundle analysis reveals:
- Which modules consume the most space
- Duplicate dependencies across chunks
- Opportunities for code splitting
- Third-party library impact on bundle size
- Dead code that can be eliminated
Key metrics to monitor:
- Initial bundle size: First load performance
- Chunk sizes: Lazy-loaded module sizes
- Third-party dependencies: External library impact
- Tree shaking effectiveness: Unused code elimination
Update and Maintenance¶
Keeping your Angular application up-to-date is crucial for security, performance, and access to new features. Angular provides automated migration tools to help upgrade between versions safely.
Angular Updates¶
The ng update command is Angular's smart update tool that not only updates packages but also runs automated
migrations to update your code for breaking changes.
# Check for available updates
ng update
# Update Angular CLI globally
npm update -g @angular/cli
# Update Angular packages
ng update @angular/core @angular/cli
# Update to next version
ng update @angular/core@next @angular/cli@next
# Update specific package
ng update @angular/material
How ng update works:
- Analyzes dependencies: Checks for compatible versions
- Runs migrations: Automatically updates code for breaking changes
- Updates package.json: Installs new versions
- Provides guidance: Shows manual steps if needed
Update strategies:
- Major versions: Follow Angular's update guide at update.angular.io
- Minor versions: Usually safe to update directly
- Patch versions: Bug fixes, safe to update immediately
Add External Libraries¶
Angular CLI provides ng add for smart package installation that goes beyond npm install by running
setup schematics that configure the package properly.
# Add Angular Material
ng add @angular/material
# Add PWA support
ng add @angular/pwa
# Add Angular Elements
ng add @angular/elements
# Add ESLint
ng add @angular-eslint/schematics
Benefits of ng add over npm install:
- Automatic configuration: Sets up necessary configuration files
- Import statements: Adds required imports to your modules
- Style integration: Includes CSS/SCSS files where needed
- Dependency resolution: Ensures compatible versions
- Project structure: Creates necessary files and folders
Popular packages to add:
- angular/material: Material Design components
- angular/pwa: Progressive Web App features
- angular/fire: Firebase integration
- ngrx/store: State management
- angular/flex-layout: Flexible layout system
Workspace Commands¶
Angular workspaces support multiple projects (applications and libraries) in a single repository. This is particularly useful for monorepos where you want to share code between different applications.
Multi-Project Workspace¶
Workspaces enable code sharing, consistent tooling, and centralized dependency management across multiple related projects.
# Generate new application in workspace
ng generate application my-second-app
# Generate library
ng generate library my-lib
# Build specific project
ng build my-second-app
# Serve specific project
ng serve my-second-app
Workspace benefits:
- Shared libraries: Create reusable components and services
- Consistent configuration: Same Angular version, build tools, and lint rules
- Code sharing: Import from libraries using TypeScript path mapping
- Unified testing: Test all projects together
- Simplified CI/CD: Single build pipeline for related projects
Library vs Application:
- Libraries: Reusable code packages (components, services, utilities)
- Applications: Deployable apps that consume libraries
Common workspace patterns:
# Create shared UI library
ng generate library shared-ui
# Create utilities library
ng generate library shared-utils
# Create feature-specific library
ng generate library feature-auth
# Create admin application
ng generate application admin-app
Useful Tips and Tricks¶
These shortcuts and advanced techniques will significantly speed up your development workflow and make you more productive with Angular CLI.
Aliases and Shortcuts¶
Angular CLI supports short aliases for commonly used commands, saving you typing time:
# Use shorter commands
ng g c my-component # instead of ng generate component
ng s # instead of ng serve
ng b # instead of ng build
ng t # instead of ng test
Complete alias reference:
g=generates=serveb=buildt=teste=e2el=lint
Dry Run¶
Preview changes before they're applied - essential for understanding what a command will do:
Benefits of dry run:
- Safety: See changes before committing to them
- Learning: Understand what files will be created/modified
- Planning: Preview complex schematics before execution
- Debugging: Troubleshoot generation issues
Help and Documentation¶
Angular CLI has comprehensive built-in help for every command:
# Get help for any command
ng help
ng generate --help
ng build --help
# Get available schematics
ng generate --help
Pro tip: Use --help with any command to see all available options and examples.
Custom Schematics¶
Extend Angular CLI with custom code generation templates for your organization's standards:
# Install third-party schematic
npm install my-custom-schematic
# Use custom schematic
ng generate my-custom-schematic:my-template
Popular third-party schematics:
- ngrx/schematics: NgRx state management templates
- angular/material: Material Design component templates
- nativescript/schematics: NativeScript mobile app templates
- Company-specific schematics: Internal templates and conventions
Common CLI Issues and Solutions¶
These are real-world problems developers encounter and their proven solutions. Keep this section handy for troubleshooting common issues.
Permission Issues¶
Problem: Permission errors when installing Angular CLI globally.
# On macOS/Linux, if you get permission errors
sudo npm install -g @angular/cli
# Better approach: use nvm to manage Node versions
nvm install node
nvm use node
npm install -g @angular/cli
Why this happens: Global npm installations require system permissions. Using Node Version Manager (nvm) gives you user-level control over Node.js installations.
Port Already in Use¶
Problem: Development server can't start because port 4200 is already in use.
# Use different port
ng serve --port 4300
# Find and kill process using port 4200
lsof -ti:4200 | xargs kill -9
Prevention:
- Use
ng serve --port 0to auto-assign an available port - Always properly stop servers with
Ctrl+Cinstead of closing terminals
Memory Issues¶
Problem: Build fails with "JavaScript heap out of memory" error.
# Increase Node.js memory limit
node --max_old_space_size=8192 ./node_modules/@angular/cli/bin/ng serve
When this happens:
- Large applications with many dependencies
- Complex build processes
- Limited system memory
- Multiple development servers running
Additional solutions:
- Close unnecessary applications
- Use
ng build --source-map=falseto reduce memory usage - Consider upgrading system memory for large projects
Common Error Patterns¶
TypeScript compilation errors: Usually indicate missing dependencies or incorrect imports Schematic errors: Often caused by incompatible versions or missing peer dependencies Build optimization errors: Typically occur with third-party libraries that aren't tree-shakable
Summary¶
The Angular CLI is an essential tool that:
- Simplifies project setup and management
- Provides consistent code generation
- Offers powerful build and optimization options
- Includes testing and quality assurance tools
- Handles dependency updates and migrations
- Supports multi-project workspaces
Remember: This module is your CLI reference guide. You don't need to memorize everything now - just bookmark it and return when you need specific functionality. Mastering the Angular CLI comes naturally through building projects.
Next Steps¶
Now that you know the Angular CLI exists and understand the basics, you're ready to:
- Start building: Create your first component (the CLI will help!)
- Learn the fundamentals: Understand Angular modules and architecture
- Return when needed: Come back to this reference for advanced CLI features
Quick Reference Card (bookmark this!):
ng new my-app- Create new projectng serve- Start development serverng generate component my-component- Create componentng build- Build for productionng test- Run testsng help- Get help for any command
The CLI will be your companion throughout the Angular development journey!