| |

Angular 3 🅰️ Angular CLI Basics

The Angular CLI is the command-line interface that drives every part of an Angular project — you use it to create, generate, serve, test, build, and update. Almost everything you do day to day goes through ng, and knowing the core commands is what makes Angular feel productive instead of fiddly.

Key point: The CLI isn’t optional tooling — it’s the standard way to work with Angular. Every file in a project is generated, built, served, and tested through it. Learn the commands once and you’ll use them for the life of the project.


What the CLI does

The CLI is a single command — ng — with subcommands. Each subcommand handles a distinct task.

  • ng new — create a new project
  • ng generate — scaffold components, services, guards, and more
  • ng serve — run the dev server with hot reload
  • ng build — compile for production
  • ng test — run unit tests
  • ng e2e — run end-to-end tests
  • ng lint — run the linter
  • ng update — upgrade Angular and dependencies
  • ng add — add a library and configure it
  • ng config — read and write CLI configuration
  • ng version — show the toolchain versions
  • ng help — open help for any command

Every command has options. Most have sensible defaults — you can run ng serve without arguments and it just works.

Why the CLI matters: Hand-editing files in an Angular project is possible but not how the framework is designed to be used. The CLI knows the conventions — folder layout, file naming, imports, module wiring. When you use it, everything stays consistent.


ng new — creating a project

ng new my-app

The CLI asks a few questions — stylesheet format, routing, SSR — then scaffolds a full project.

Common flags:

FlagPurpose
--routingAdd routing module
--style=cssStylesheet format (css, scss, less)
--ssrEnable server-side rendering
--standaloneUse standalone components (default in v19+)
--skip-testsDon’t generate test files
--skip-gitDon’t initialize a Git repo
--prefix=appComponent selector prefix

Example:

ng new shop --routing --style=scss --ssr

Creates a project called shop with routing, SCSS, and SSR enabled.

What it generates:

  • src/ — application source
  • angular.json — build configuration
  • package.json — dependencies and scripts
  • tsconfig.json — TypeScript configuration
  • src/app/ — the root component and configuration

After ng new, the project builds and serves immediately. No setup required.

Why defaults are fine: The prompts ask about things you may not have opinions about yet. Take the defaults for a first project — you can change them later.


ng generate — scaffolding code

The generate command creates files that follow Angular conventions. It writes the correct imports, wiring, and test files.

Common schematic shortcuts:

CommandWhat it creates
ng g c NAMEComponent
ng g s NAMEService
ng g d NAMEDirective
ng g p NAMEPipe
ng g g NAMEGuard
ng g i NAMEInterface
ng g e NAMEEnum
ng g cl NAMEClass
ng g m NAMEModule
ng g r NAMEResolver

g is short for generate. c is short for component. The shorthand is used constantly.

Example — a component:

ng generate component user-list

Produces:

  • user-list.component.ts
  • user-list.component.html
  • user-list.component.css
  • user-list.component.spec.ts
  • Updates the module or standalone imports

Example — a service:

ng generate service user

Produces user.service.ts and user.service.spec.ts.

Common flags:

FlagPurpose
--flatDon’t create a folder
--skip-testsNo spec file
--inline-templateTemplate inside the .ts file
--inline-styleStyles inside the .ts file
--standaloneStandalone component
--change-detection=OnPushUse OnPush change detection
--prefix=myCustom prefix
--dry-runPreview without writing files

Preview with --dry-run:

ng generate component user --dry-run

Shows what would be created without touching the filesystem. Useful before committing to a shape.

Generate in a specific path:

ng generate component features/users/list

Creates the files in src/app/features/users/list/.

Why use ng generate instead of writing files: The CLI writes the correct boilerplate — imports, decorators, lifecycle methods, and test scaffolding — tailored to your Angular version. Hand-writing those files is error-prone and slow.


ng serve — running the dev server

ng serve

Builds the app and serves it at http://localhost:4200. Watches source files and rebuilds on change. The browser reloads automatically (or updates without a full reload in some setups).

Common flags:

FlagPurpose
--port 4300Use a different port
--host 0.0.0.0Listen on all network interfaces
--openOpen the browser automatically
--configuration developmentUse a named config
--pollUse polling for file watching
--proxy-config proxy.conf.jsonUse a proxy for API calls

Example:

ng serve --open --port 4300

Runs at http://localhost:4300 and opens the browser.

Proxy configuration — for developing against a backend:

// proxy.conf.json
{
  "/api": {
    "target": "http://localhost:3000",
    "secure": false
  }
}
ng serve --proxy-config proxy.conf.json

Requests to /api/* are forwarded to http://localhost:3000.

Why use the proxy: During development, your backend may run on a different port. The proxy lets the frontend call /api/... without CORS issues.


ng build — compiling for production

ng build

Compiles the app into dist/. By default, Angular’s production build enables:

  • Ahead-of-Time compilation
  • Tree shaking
  • Minification
  • Dead code elimination
  • Output hashing for cache busting

Common flags:

FlagPurpose
--configuration productionExplicit production build
--base-href /app/Set base URL
--output-path dist/mysiteCustom output folder
--source-mapInclude source maps
--stats-jsonEmit a stats file for analysis
--named-chunksHuman-readable chunk names

Example:

ng build --configuration production --base-href /shop/

Output structure:

dist/my-app/
├── browser/
│   ├── index.html
│   ├── main-ABCD1234.js
│   ├── polyfills-EFGH5678.js
│   └── styles-IJKL9012.js
└── server/          (if SSR)

The hashed filenames are cache-busting — a new build produces new hashes, so browsers fetch the new files.

Why the production build is different: Development builds are fast but unoptimized. Production builds are slower but produce small, efficient bundles. Never deploy a development build.


ng test and ng e2e — testing

ng test

Runs unit tests with the configured test runner. Watches for changes by default.

Flags:

FlagPurpose
--watch=falseRun once and exit
--code-coverageGenerate a coverage report
--browsers=ChromeHeadlessChoose browser
--include=**/user*.spec.tsFilter test files
ng test --watch=false --code-coverage

Runs all tests once and generates coverage.

ng e2e

Runs end-to-end tests with the configured tool (Protractor historically; modern projects often use Cypress or Playwright added separately).

Why CLI-based tests: The CLI configures the test runner, browser, and TypeScript compilation. You write specs and run ng test — everything else is handled.


ng update and ng add

ng update upgrades Angular and its dependencies, running automated migrations where possible.

ng update @angular/cli @angular/core

The CLI checks for breaking changes, updates package.json, and runs migration schematics that adjust your code.

ng add installs a library and configures it in one step.

ng add @angular/material

This installs the package, adds theme files, updates angular.json, and configures providers. Compare this to npm install followed by manual setup — much faster.

Why use ng update: Angular’s major versions ship every 6 months. Running ng update handles the mechanical parts — package versions, deprecated APIs, config changes — automatically. Manual upgrades miss things.


ng config and ng version

ng config

Reads or writes CLI configuration, stored in angular.json.

ng config projects.my-app.architect.build.options.outputPath dist/custom
ng version

Shows the CLI, Node, npm, and OS versions, plus Angular package versions inside a project.

Why ng version matters: When something goes wrong, the first step is knowing exactly what versions you have. ng version shows the whole chain at once.


Workspace vs project

An Angular workspace can contain multiple projects — the main app plus libraries.

ng new my-workspace --no-create-application
ng generate application app1
ng generate application app2
ng generate library my-lib

Inside a workspace, the CLI commands accept a --project flag to target a specific project.

Why workspaces: Monorepos are common in large teams. Angular’s workspace support lets multiple apps and libraries live in one repo with shared tooling.


Complete Example Session

# ============================================
# PART 1: CREATE A NEW PROJECT
# ============================================

ng new my-app --routing --style=scss
# [ ? Do you want to enable Server-Side Rendering (SSR)? No ]
# [ ✔ Packages installed successfully. ]

cd my-app

# ============================================
# PART 2: GENERATE A COMPONENT
# ============================================

ng generate component user-list
# [ CREATE src/app/user-list/user-list.component.ts ]
# [ CREATE src/app/user-list/user-list.component.html ]
# [ CREATE src/app/user-list/user-list.component.css ]
# [ CREATE src/app/user-list/user-list.component.spec.ts ]

# ============================================
# PART 3: GENERATE A SERVICE
# ============================================

ng generate service user
# [ CREATE src/app/user.service.ts ]
# [ CREATE src/app/user.service.spec.ts ]

# ============================================
# PART 4: GENERATE A GUARD
# ============================================

ng generate guard auth
# [ ? Which type of guard? CanActivate ]
# [ CREATE src/app/auth.guard.ts ]
# [ CREATE src/app/auth.guard.spec.ts ]

# ============================================
# PART 5: DRY RUN
# ============================================

ng generate component temp --dry-run
# [ CREATE src/app/temp/temp.component.ts ]
# [ CREATE src/app/temp/temp.component.html ]
# (nothing written to disk)

# ============================================
# PART 6: SERVE THE APP
# ============================================

ng serve --open
# [ ✔ Browser application bundle generation complete. ]
# [ Local:   http://localhost:4200/ ]

# ============================================
# PART 7: BUILD FOR PRODUCTION
# ============================================

ng build
# [ ✔ Browser application bundle generation complete. ]
# [ Output location: dist/my-app ]

# ============================================
# PART 8: RUN TESTS
# ============================================

ng test --watch=false
# [ Chrome Headless: Executed 5 of 5 SUCCESS ]

# ============================================
# PART 9: ADD A LIBRARY
# ============================================

ng add @angular/material
# [ ? Choose a prebuilt theme name: Indigo/Pink ]
# [ ? Set up global Angular Material typography styles? Yes ]
# [ ? Include the Angular animations module? Include and enable ]
# [ UPDATE package.json ]
# [ UPDATE src/app/app.config.ts ]

# ============================================
# PART 10: UPDATE ANGULAR
# ============================================

ng update @angular/cli @angular/core
# [ Package '@angular/cli' is already up to date. ]
# [ Package '@angular/core' is already up to date. ]

Quick Reference

Main Commands

CommandPurpose
ng newCreate a project
ng generate / ng gScaffold code
ng serveDev server
ng buildProduction build
ng testUnit tests
ng e2eEnd-to-end tests
ng lintLint
ng updateUpgrade
ng addAdd a library
ng configManage config
ng versionShow versions
ng helpHelp

Generate Schematics

CommandCreates
ng g component NAMEComponent
ng g service NAMEService
ng g directive NAMEDirective
ng g pipe NAMEPipe
ng g guard NAMERoute guard
ng g interface NAMEInterface
ng g enum NAMEEnum
ng g class NAMEClass
ng g module NAMEModule
ng g resolver NAMERoute resolver

ng new Flags

FlagEffect
--routingAdd routing
--style=scssStylesheet format
--ssrServer-side rendering
--standaloneStandalone components
--skip-testsNo spec files
--skip-gitNo Git init
--prefix=appSelector prefix

ng serve Flags

FlagEffect
--port 4300Custom port
--openOpen browser
--host 0.0.0.0All interfaces
--proxy-config FILEAPI proxy
--pollFile watcher polling

ng build Flags

FlagEffect
--configuration productionProduction
--base-href /app/Base URL
--output-path dist/siteOutput folder
--source-mapInclude source maps
--stats-jsonEmit stats file

ng test Flags

FlagEffect
--watch=falseRun once
--code-coverageCoverage report
--browsers=ChromeHeadlessHeadless browser
--include=PATTERNFilter specs

Generate Flags

FlagEffect
--flatNo folder
--skip-testsNo spec file
--inline-templateInline HTML
--inline-styleInline CSS
--standaloneStandalone
--dry-runPreview
--change-detection=OnPushOnPush strategy

Workspace Commands

CommandPurpose
ng new --no-create-applicationWorkspace only
ng generate application NAMEAdd an app
ng generate library NAMEAdd a library
ng build PROJECTBuild a specific project
ng serve PROJECTServe a specific project

Best Practices

Do This:

# Use the CLI for everything
ng generate component user-list                    # ✅

# Preview changes
ng generate component user --dry-run               # ✅

# Use shorthand for common tasks
ng g c user-list                                   # ✅

# Serve with proxy for a backend
ng serve --proxy-config proxy.conf.json            # ✅

# Build for production explicitly
ng build --configuration production                # ✅

# Use ng add instead of npm install for Angular libraries
ng add @angular/material                           # ✅

# Update with the CLI
ng update @angular/cli @angular/core               # ✅

Don’t Do This:

# Don't hand-write scaffolding files
# Use ng generate for components, services, etc.   # ⚠️

# Don't deploy a development build
ng build                                           # ⚠️  use --configuration production

# Don't fight the CLI structure
# Match its conventions                              # ❌

# Don't skip tests just to speed up scaffolding
ng g c user --skip-tests                           # ⚠️  keep specs

# Don't install libraries with npm and configure by hand
npm install @angular/material                      # ⚠️  use ng add

# Don't update package.json versions manually
# Use ng update                                      # ❌

# Don't run ng serve on port conflicts without --port
ng serve                                           # ⚠️  use --port 4300

Common Pitfalls

PitfallProblemSolution
ng: command not foundCLI not on PATHReinstall or fix PATH
Wrong port in useng serve fails--port 4300
Hand-scaffolded filesMissing importsUse ng generate
Deployed dev buildLarge, slowUse --configuration production
ng update skips testsSilent breakageRun ng test after
Manual library setupConfig incompleteUse ng add
Wrong schematic flagsWrong shapeCheck ng g c --help
Workspace project confusionWrong targetUse --project

Real-World Examples

1. Create a project with routing

ng new shop --routing

Adds a routing module.

2. Create with SCSS and SSR

ng new site --style=scss --ssr

Full setup.

3. Generate a component

ng g c user-list

Component files plus module wiring.

4. Generate a service

ng g s user

Service plus spec file.

5. Generate a guard

ng g g auth

Prompts for guard type.

6. Dry-run a generation

ng g c temp --dry-run

Preview without writing.

7. Serve on a custom port

ng serve --port 4300 --open

Dev server with auto-open.

8. Proxy API calls

ng serve --proxy-config proxy.conf.json

Forward /api to backend.

9. Build for production

ng build --configuration production

Optimized output in dist/.

10. Run tests once

ng test --watch=false --code-coverage

CI-friendly test run with coverage.

11. Add Angular Material

ng add @angular/material

Installs and configures in one step.

12. Update Angular

ng update @angular/cli @angular/core

Automated migration.

13. Show versions

ng version

Full toolchain report.

14. Workspace with two apps

ng new ws --no-create-application
cd ws
ng generate application app1
ng generate application app2

Multiple apps, one repo.

15. Build a specific project in a workspace

ng build app1

Targets that project.


Visual: Common CLI Commands

┌──────────────────────────────────────────────┐
│  Project setup                               │
│                                              │
│  ng new my-app          create project       │
│  ng g c NAME            add component        │
│  ng g s NAME            add service          │
│                                              │
├──────────────────────────────────────────────┤
│  Development                                 │
│                                              │
│  ng serve               run dev server       │
│  ng test                run unit tests       │
│  ng e2e                 run end-to-end       │
│                                              │
├──────────────────────────────────────────────┤
│  Production                                  │
│                                              │
│  ng build               compile for deploy   │
│  ng update              upgrade Angular      │
│  ng add                 install a library    │
│                                              │
└──────────────────────────────────────────────┘

Visual: Generate Workflow

┌──────────────────────────────────────────────┐
│  ng g c user-list                            │
│       │                                      │
│       ▼                                      │
│  Creates:                                    │
│    user-list.component.ts                    │
│    user-list.component.html                  │
│    user-list.component.css                   │
│    user-list.component.spec.ts               │
│       │                                      │
│       ▼                                      │
│  Wires into module or standalone imports     │
│                                              │
│  Ready to edit — no setup needed             │
│                                              │
└──────────────────────────────────────────────┘

Visual: Serve Workflow

┌──────────────────────────────────────────────┐
│  ng serve                                    │
│       │                                      │
│       ├──► compiles TypeScript               │
│       ├──► bundles templates & styles        │
│       ├──► serves at :4200                   │
│       └──► watches source                    │
│                                              │
│  Edit a file                                 │
│       │                                      │
│       ▼                                      │
│  Incremental rebuild + browser reload        │
│                                              │
└──────────────────────────────────────────────┘

Visual: Build Output

dist/my-app/
├── browser/
│   ├── index.html
│   ├── main.a1b2c3d4.js         ← app code
│   ├── polyfills.e5f6g7h8.js    ← runtime shims
│   ├── styles.i9j0k1l2.css      ← global styles
│   └── assets/                  ← images, etc.
└── server/                       ← if SSR
    └── main.m3n4o5p6.js

Filenames contain hashes for cache-busting.

Visual: Workspace Structure

my-workspace/
├── angular.json
├── package.json
├── projects/
│   ├── app1/       ← application 1
│   ├── app2/       ← application 2
│   └── my-lib/     ← shared library
└── node_modules/

Summary

CommandPurpose
ng new NAMECreate a project
ng g c NAMEGenerate component
ng g s NAMEGenerate service
ng serveRun dev server
ng buildProduction build
ng testUnit tests
ng e2eEnd-to-end tests
ng add PKGAdd a library
ng updateUpgrade Angular
ng configManage configuration
ng versionShow toolchain
ng helpHelp for any command

Key takeaways:

  • The Angular CLI (ng) is the primary interface for all Angular tooling
  • ng new creates a full project — no manual setup
  • ng generate (or ng g) scaffolds components, services, directives, and more with the correct wiring
  • Use --dry-run to preview generation without writing files
  • ng serve runs the dev server with hot reload at http://localhost:4200
  • Use --proxy-config to route API calls to a backend during development
  • ng build compiles for production — tree-shaken, minified, hashed
  • ng test and ng e2e run unit and end-to-end tests
  • ng add installs a library and configures it in one step — better than manual npm install
  • ng update handles Angular version upgrades and migrations
  • Workspaces hold multiple apps and libraries in one repository
  • Inside a project, the CLI uses the local version from node_modules

Remember: The CLI is the tool you’ll use every day. ng new to start, ng g to scaffold, ng serve to develop, ng build to ship. Use --dry-run before generating, --proxy-config for backend work, and ng add for libraries. Once these commands are habits, Angular development becomes fast and predictable.


Stop using slow, ad-bloated tool sites! 🤮

🔎 Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)

⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free

🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!