Table of Contents
- Prerequisites
- Installing Angular CLI
- Creating a New Angular Project
- Understanding the Project Structure
- Key Angular CLI Commands
- Advanced Angular CLI Features
- Troubleshooting Common Issues
- Conclusion
- 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
-gflag 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 avoidsudo).
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:
- Would you like to add Angular routing? (Yes/No)
- Type
Yesif you plan to use Angular Router for navigation (recommended for most apps).
- Type
- Which stylesheet format would you like to use? (CSS, SCSS, Sass, Less, Stylus)
- Choose your preferred format (e.g.,
SCSSfor modular styles).
- Choose your preferred format (e.g.,
Project Creation Process
The CLI will:
- Create a new folder
my-angular-appwith a preconfigured project structure. - Install dependencies (via
npm install). - Set up TypeScript, ESLint, and testing tools (Karma for unit tests, Cypress for E2E tests).
Navigate to the Project
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 athttp://localhost:4200.- Custom Port: Use
--port 4201to 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/.cssfiles) - Specify a module:
ng g c user-profile --module admin.module.ts(adds the component toadmin.module.tsinstead ofapp.module.ts).
Generating Directives, Pipes, and Services
Angular CLI can generate other core artifacts too:
| Artifact | Command | Shorthand |
|---|---|---|
| Directive | ng generate directive my-dir | ng g d my-dir |
| Pipe | ng generate pipe my-pipe | ng g p my-pipe |
| Service | ng generate service my-service | ng 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 aadmin-routing.module.tsfile 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-appfolder. - Production Configuration: By default, Angular CLI uses the
productionconfiguration (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 testng testOpens a browser with test results; watches for changes and re-runs tests.
-
End-to-End Tests (Cypress): Run with
ng e2eng e2eLaunches 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 configexport const environment = { production: false, apiUrl: 'http://localhost:3000' };environment.prod.ts: Production configexport 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/cliand ensure Node.js is in your system’sPATH.
Port 4200 Already in Use
- Fix: Specify a different port with
ng serve --port 4201.
Dependency Conflicts
- Fix: Delete
node_modulesandpackage-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.