cyberangles guide

Step-by-Step Guide to Angular CLI

Angular CLI (Command-Line Interface) is a powerful tool developed by the Angular team to streamline and simplify the development workflow for Angular applications. Whether you’re a beginner setting up your first Angular project or an experienced developer looking to automate repetitive tasks, Angular CLI is an indispensable tool. It handles project scaffolding, code generation, testing, building, and deployment—all with simple commands. This guide will walk you through everything you need to know about Angular CLI, from installation to advanced features, with clear examples and explanations. By the end, you’ll be confident in using CLI commands to boost your Angular development productivity.

Table of Contents

  1. Prerequisites
  2. Installing Angular CLI
  3. Creating a New Angular Project
  4. Understanding the Project Structure
  5. Key Angular CLI Commands
  6. Advanced Angular CLI Features
  7. Troubleshooting Common Issues
  8. Conclusion
  9. References

Prerequisites

Before installing Angular CLI, ensure your system meets these requirements:

  • Node.js: Angular CLI requires Node.js version 18.x or later. Download it from nodejs.org.
  • npm (Node Package Manager): Included with Node.js. Verify npm version with npm -v (requires npm 9.x or later).

To check your Node.js and npm versions:

node -v   # Output: v18.x.x or higher  
npm -v    # Output: 9.x.x or higher  

Installing Angular CLI

Angular CLI is installed globally via npm to make it accessible across all projects. Run the following command in your terminal:

npm install -g @angular/cli  
  • The -g flag installs the package globally.
  • If you encounter permission issues (common on macOS/Linux), use sudo npm install -g @angular/cli (or configure npm to use a user directory to avoid sudo).

Verify Installation:
Check if Angular CLI is installed correctly by running:

ng version   # or ng v  

You’ll see output like this, confirming the CLI version and system details:

Angular CLI: 16.2.0  
Node: 18.17.1  
Package Manager: npm 9.6.7  
OS: darwin x64  

Creating a New Angular Project

With Angular CLI installed, you can scaffold a new project in seconds. Use the ng new command:

ng new my-angular-app  

What Happens Next?

The CLI will prompt you with two key questions:

  1. Would you like to add Angular routing? (Yes/No)
    • Type Yes if you plan to use Angular Router for navigation (recommended for most apps).
  2. Which stylesheet format would you like to use? (CSS, SCSS, Sass, Less, Stylus)
    • Choose your preferred format (e.g., SCSS for modular styles).

Project Creation Process

The CLI will:

  • Create a new folder my-angular-app with a preconfigured project structure.
  • Install dependencies (via npm install).
  • Set up TypeScript, ESLint, and testing tools (Karma for unit tests, Cypress for E2E tests).

Once created, move into the project directory:

cd my-angular-app  

Understanding the Project Structure

Angular CLI generates a standardized folder structure. Here’s a breakdown of key files and directories:

my-angular-app/  
├── node_modules/        # Dependencies (auto-installed)  
├── src/                 # Source code for the application  
│   ├── app/             # Root module and components  
│   │   ├── app.component.ts   # Root component logic  
│   │   ├── app.component.html # Root component template  
│   │   ├── app.component.css  # Root component styles  
│   │   ├── app.component.spec.ts # Root component tests  
│   │   └── app.module.ts      # Root module (declares components)  
│   ├── assets/          # Static files (images, fonts, etc.)  
│   ├── environments/    # Environment-specific configs (dev/prod)  
│   ├── index.html       # Main HTML file (entry point)  
│   └── main.ts          # Main TypeScript file (bootstraps the app)  
├── angular.json         # CLI configuration (build, serve, test settings)  
├── package.json         # Project dependencies and scripts  
├── tsconfig.json        # TypeScript compiler options  
└── README.md            # Project documentation  

Key Files:

  • angular.json: Controls CLI behavior (e.g., build output paths, test settings).
  • src/app/app.module.ts: The root module that declares components and imports modules.

Key Angular CLI Commands

Angular CLI’s power lies in its ability to automate repetitive tasks. Below are the most commonly used commands.

Serving the Application

To run the app locally during development, use ng serve:

ng serve --open  
  • --open (or -o): Automatically opens the app in your default browser at http://localhost:4200.
  • Custom Port: Use --port 4201 to change the port (e.g., if 4200 is in use).

The app will reload automatically when you make code changes (hot module replacement).

Generating Components

Components are the building blocks of Angular apps. Use ng generate component (or ng g c for short) to create one:

ng generate component user-profile   # Full command  
# Shorthand: ng g c user-profile  

What Gets Generated?

The CLI creates a new folder src/app/user-profile with 4 files:

  • user-profile.component.ts: Component logic (class, decorator).
  • user-profile.component.html: Template (view).
  • user-profile.component.css/scss: Styles.
  • user-profile.component.spec.ts: Unit test file.

It also updates app.module.ts to declare the new component in the declarations array.

Customization Options

  • Skip test files: ng g c user-profile --skip-tests
  • Inline template/style: ng g c user-profile -t -s (no separate .html/.css files)
  • Specify a module: ng g c user-profile --module admin.module.ts (adds the component to admin.module.ts instead of app.module.ts).

Generating Directives, Pipes, and Services

Angular CLI can generate other core artifacts too:

ArtifactCommandShorthand
Directiveng generate directive my-dirng g d my-dir
Pipeng generate pipe my-pipeng g p my-pipe
Serviceng generate service my-serviceng g s my-service

Example: Generate a Service

ng g s data-service  

By default, services are injectable with providedIn: 'root', making them singletons available app-wide:

@Injectable({ providedIn: 'root' })  
export class DataService { ... }  

Generating Modules

Modules organize components, directives, and pipes. Use ng generate module to create a feature module:

ng generate module admin --routing  
  • --routing: Adds a admin-routing.module.ts file for module-specific routing.

This generates:

  • admin.module.ts: The feature module.
  • admin-routing.module.ts: Routing configuration for the module.

Building for Production

To create an optimized production build, use ng build:

ng build  
  • Output: Files are generated in the dist/my-angular-app folder.
  • Production Configuration: By default, Angular CLI uses the production configuration (minifies code, enables tree-shaking).

For staging or custom environments, use --configuration:

ng build --configuration staging  

Running Tests

Angular CLI integrates with testing tools out of the box:

  • Unit Tests (Karma + Jasmine): Run with ng test

    ng test  

    Opens a browser with test results; watches for changes and re-runs tests.

  • End-to-End Tests (Cypress): Run with ng e2e

    ng e2e  

    Launches Cypress to run automated browser tests.

Advanced Angular CLI Features

Custom Schematics

Angular CLI uses “schematics” to generate code. You can create custom schematics to automate project-specific workflows (e.g., generating a “dashboard” component with predefined logic).

To learn more: Angular Schematics Guide.

Multi-Project Workspaces

For large apps, use Angular CLI workspaces to manage multiple projects (e.g., a main app, a shared library).

Create a Workspace:

ng new my-workspace --create-application false  
cd my-workspace  

Add Projects:

  • Add an app: ng generate application app1
  • Add a library: ng generate library shared-utils

Workspaces are configured in angular.json, where you can define project-specific settings.

Environment Configuration

Use src/environments/ to manage environment-specific variables (e.g., API URLs).

  • environment.ts: Development config
    export const environment = { production: false, apiUrl: 'http://localhost:3000' };  
  • environment.prod.ts: Production config
    export const environment = { production: true, apiUrl: 'https://api.myapp.com' };  

Build with a Specific Environment:

ng build --configuration production   # Uses environment.prod.ts  

Troubleshooting Common Issues

”ng: command not found”

  • Cause: Angular CLI not installed globally or Node.js path not set.
  • Fix: Reinstall CLI with npm install -g @angular/cli and ensure Node.js is in your system’s PATH.

Port 4200 Already in Use

  • Fix: Specify a different port with ng serve --port 4201.

Dependency Conflicts

  • Fix: Delete node_modules and package-lock.json, then reinstall dependencies:
    rm -rf node_modules package-lock.json  
    npm install  

Conclusion

Angular CLI is a game-changer for Angular development, reducing boilerplate and streamlining workflows. From scaffolding projects to generating components and building for production, CLI commands save time and ensure consistency.

Start small: create a project, experiment with ng generate, and explore angular.json to customize your setup. As you grow, dive into advanced features like workspaces and schematics to scale your workflow.

References