Angular CLI
Introduction
The Angular Command Line Interface (CLI) is a powerful tool that simplifies the development process for Angular applications. It provides a set of commands that automate common tasks like creating projects, generating code, running tests, and building for production. The CLI is essential for Angular developers as it enforces best practices and consistent project structure, allowing you to focus more on building features rather than configuration details.
In this guide, you'll learn how to use the Angular CLI to accelerate your development workflow and maintain a consistent project structure.
Installing Angular CLI
Before you can use the Angular CLI, you need to install it on your system. The CLI requires Node.js and npm (Node Package Manager).
Prerequisites
- Node.js (version 14.x or higher)
- npm (version 6.x or higher)
You can check your current versions by running:
node -v
npm -v
Installation Steps
To install the Angular CLI globally on your system, run:
npm install -g @angular/cli
After installation, you can verify the CLI installation by checking its version:
ng version
The output will look something like this:
_ _ ____ _ ___
/ \ _ __ __ _ _ _| | __ _ _ __ / ___| | |_ _|
/ △ \ | '_ \ / _` | | | | |/ _` | '__| | | | | | |
/ ___ \| | | | (_| | |_| | | (_| | | | |___| |___ | |
/_/ \_\_| |_|\__, |\__,_|_|\__,_|_| \____|_____|___|
|___/
Angular CLI: 16.2.0
Node: 18.16.0
Package Manager: npm 9.5.1
OS: darwin arm64
Angular: 16.2.0
... animations, cli, common, compiler, compiler-cli, core, forms
... platform-browser, platform-browser-dynamic, router
Creating Your First Angular Project
Once the CLI is installed, you can create a new Angular application with a single command:
ng new my-first-angular-app
The CLI will ask you a few questions to customize your project:
- Routing: Whether to include Angular's routing module
- CSS: What format to use for stylesheets (CSS, SCSS, Sass, Less)
For beginners, I recommend selecting "Yes" for routing and "CSS" for the stylesheet format.
Example:
ng new my-first-angular-app --routing=true --style=css
This command creates a new project folder with all the necessary files and dependencies pre-configured. The output will show the progress of file creation and dependency installation:
CREATE my-first-angular-app/angular.json (3029 bytes)
CREATE my-first-angular-app/package.json (1073 bytes)
CREATE my-first-angular-app/tsconfig.json (863 bytes)
CREATE my-first-angular-app/README.md (1061 bytes)
CREATE my-first-angular-app/.editorconfig (274 bytes)
CREATE my-first-angular-app/.gitignore (548 bytes)
CREATE my-first-angular-app/src/favicon.ico (948 bytes)
CREATE my-first-angular-app/src/index.html (296 bytes)
CREATE my-first-angular-app/src/main.ts (214 bytes)
CREATE my-first-angular-app/src/styles.css (80 bytes)
... [many more files]
✔ Packages installed successfully.
Running Your Angular Application
After creating your project, you can navigate to the project directory and start a development server:
cd my-first-angular-app
ng serve
By default, the application runs on http://localhost:4200/
. The ng serve
command compiles your app and reloads it automatically whenever you make changes to the source files.
You can also use the --open
flag to automatically open the application in your default browser:
ng serve --open
Or use the shorthand:
ng serve -o
Generating Angular Components and Other Code
One of the most powerful features of the Angular CLI is its ability to generate various parts of your application using the ng generate
command (or just ng g
).
Generating Components
Components are the fundamental building blocks in Angular applications. To generate a new component:
ng generate component my-component
Or using the shorthand:
ng g c my-component
This command creates:
- A component class file (
my-component.component.ts
) - A template file (
my-component.component.html
) - A CSS file (
my-component.component.css
) - A test specification file (
my-component.component.spec.ts
)
The component is also automatically registered in the nearest module.
Example Output:
CREATE src/app/my-component/my-component.component.css (0 bytes)
CREATE src/app/my-component/my-component.component.html (25 bytes)
CREATE src/app/my-component/my-component.component.spec.ts (614 bytes)
CREATE src/app/my-component/my-component.component.ts (282 bytes)
UPDATE src/app/app.module.ts (394 bytes)
Other Common Generation Commands
The CLI can generate various types of Angular artifacts:
# Generate a service
ng generate service my-service
# Generate a module
ng generate module my-module
# Generate a directive
ng generate directive my-directive
# Generate a pipe
ng generate pipe my-pipe
# Generate an interface
ng generate interface my-interface
# Generate a class
ng generate class my-class
Project Structure
Let's take a look at the basic project structure that the Angular CLI creates:
my-first-angular-app/
├── node_modules/ # Third-party libraries
├── src/ # Source files for the app
│ ├── app/ # App components and modules
│ │ ├── app.component.css
│ │ ├── app.component.html
│ │ ├── app.component.spec.ts
│ │ ├── app.component.ts
│ │ └── app.module.ts
│ ├── assets/ # Static assets like images
│ ├── environments/ # Environment-specific config
│ ├── favicon.ico # Favicon for the app
│ ├── index.html # Main HTML page
│ ├── main.ts # Entry point for the app
│ └── styles.css # Global styles
├── angular.json # Angular workspace config
├── package.json # npm package dependencies
├── tsconfig.json # TypeScript compiler config
└── ... other config files
Building Your Application for Production
When you're ready to deploy your Angular application, the CLI provides a command to create an optimized production build:
ng build
For a production build with optimizations like minification and ahead-of-time (AOT) compilation:
ng build --configuration production
This command creates a dist/
directory with your compiled application ready for deployment.
Real-World Example: Creating a Todo List Application
Let's use the Angular CLI to build a simple todo list application, demonstrating how the CLI streamlines the development process:
Step 1: Create a new project with routing
ng new todo-app --routing=true --style=css
cd todo-app
Step 2: Generate components for our todo app
ng generate component components/todo-list
ng generate component components/todo-item
ng generate component components/todo-form
Step 3: Generate a service for managing todos
ng generate service services/todo
Step 4: Generate an interface for our todo items
ng generate interface models/todo
Now let's implement the Todo interface in src/app/models/todo.ts
:
export interface Todo {
id: number;
title: string;
completed: boolean;
createdAt: Date;
}
Implement the Todo service in src/app/services/todo.service.ts
:
import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';
import { Todo } from '../models/todo';
@Injectable({
providedIn: 'root'
})
export class TodoService {
private todos: Todo[] = [];
private todosSubject = new BehaviorSubject<Todo[]>([]);
constructor() {
// Initial todos
this.todos = [
{ id: 1, title: 'Learn Angular', completed: false, createdAt: new Date() },
{ id: 2, title: 'Build a Todo App', completed: false, createdAt: new Date() }
];
this.updateTodos();
}
getTodos(): Observable<Todo[]> {
return this.todosSubject.asObservable();
}
addTodo(title: string): void {
const newTodo: Todo = {
id: this.generateId(),
title,
completed: false,
createdAt: new Date()
};
this.todos = [...this.todos, newTodo];
this.updateTodos();
}
toggleComplete(id: number): void {
this.todos = this.todos.map(todo => {
if (todo.id === id) {
return { ...todo, completed: !todo.completed };
}
return todo;
});
this.updateTodos();
}
deleteTodo(id: number): void {
this.todos = this.todos.filter(todo => todo.id !== id);
this.updateTodos();
}
private updateTodos(): void {
this.todosSubject.next([...this.todos]);
}
private generateId(): number {
return this.todos.length > 0
? Math.max(...this.todos.map(todo => todo.id)) + 1
: 1;
}
}
Now you can implement the components using the service to create a complete todo application. This example demonstrates how the Angular CLI helps you quickly scaffold a project with proper structure and organization.
Essential CLI Commands Reference
Here's a quick reference of the most common Angular CLI commands:
Command | Description |
---|---|
ng new [name] | Create a new Angular project |
ng serve | Start the development server |
ng generate component [name] | Generate a new component |
ng generate service [name] | Generate a new service |
ng generate module [name] | Generate a new module |
ng build | Build the application |
ng test | Run unit tests |
ng e2e | Run end-to-end tests |
ng update | Update Angular version |
ng add [package] | Add a library to your project |
ng help | Display help for available commands |
Angular CLI Configuration
The Angular CLI uses the angular.json
file to store project configuration. This file contains settings for:
- Project structure
- Build options
- Test configurations
- Linting rules
- And more
You can customize this file to change how your application is built and served. For example, you can:
- Change the output directory for builds
- Modify the base URL for your application
- Configure optimization settings
- Set up environment-specific builds
Summary
The Angular CLI is an essential tool that simplifies and accelerates Angular development. In this guide, we've covered:
- Installing the Angular CLI
- Creating a new Angular project
- Running the development server
- Generating components and services
- Building for production
- Understanding the project structure
- Creating a real-world todo application
By mastering the Angular CLI, you'll significantly improve your productivity and ensure your Angular applications follow best practices. The CLI abstracts away complex configuration, letting you focus on writing great code.
Additional Resources
Exercises
- Create a new Angular application called "profile-app" with routing enabled.
- Generate components for "Home", "About", and "Contact" pages.
- Generate a service called "UserService" to manage user data.
- Configure the routing module to navigate between these pages.
- Build the application for production and examine the output files.
- Try generating a new module with routing and add a component to this module.
- Experiment with the
--dry-run
flag to see what a command will do without actually executing it.
By completing these exercises, you'll gain practical experience using the Angular CLI to build and structure Angular applications efficiently.
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)