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 projectng generate— scaffold components, services, guards, and moreng serve— run the dev server with hot reloadng build— compile for productionng test— run unit testsng e2e— run end-to-end testsng lint— run the linterng update— upgrade Angular and dependenciesng add— add a library and configure itng config— read and write CLI configurationng version— show the toolchain versionsng 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:
| Flag | Purpose |
|---|---|
--routing | Add routing module |
--style=css | Stylesheet format (css, scss, less) |
--ssr | Enable server-side rendering |
--standalone | Use standalone components (default in v19+) |
--skip-tests | Don’t generate test files |
--skip-git | Don’t initialize a Git repo |
--prefix=app | Component 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 sourceangular.json— build configurationpackage.json— dependencies and scriptstsconfig.json— TypeScript configurationsrc/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:
| Command | What it creates |
|---|---|
ng g c NAME | Component |
ng g s NAME | Service |
ng g d NAME | Directive |
ng g p NAME | Pipe |
ng g g NAME | Guard |
ng g i NAME | Interface |
ng g e NAME | Enum |
ng g cl NAME | Class |
ng g m NAME | Module |
ng g r NAME | Resolver |
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.tsuser-list.component.htmluser-list.component.cssuser-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:
| Flag | Purpose |
|---|---|
--flat | Don’t create a folder |
--skip-tests | No spec file |
--inline-template | Template inside the .ts file |
--inline-style | Styles inside the .ts file |
--standalone | Standalone component |
--change-detection=OnPush | Use OnPush change detection |
--prefix=my | Custom prefix |
--dry-run | Preview 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 generateinstead 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:
| Flag | Purpose |
|---|---|
--port 4300 | Use a different port |
--host 0.0.0.0 | Listen on all network interfaces |
--open | Open the browser automatically |
--configuration development | Use a named config |
--poll | Use polling for file watching |
--proxy-config proxy.conf.json | Use 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:
| Flag | Purpose |
|---|---|
--configuration production | Explicit production build |
--base-href /app/ | Set base URL |
--output-path dist/mysite | Custom output folder |
--source-map | Include source maps |
--stats-json | Emit a stats file for analysis |
--named-chunks | Human-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:
| Flag | Purpose |
|---|---|
--watch=false | Run once and exit |
--code-coverage | Generate a coverage report |
--browsers=ChromeHeadless | Choose browser |
--include=**/user*.spec.ts | Filter 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. Runningng updatehandles 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 versionmatters: When something goes wrong, the first step is knowing exactly what versions you have.ng versionshows 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
| Command | Purpose |
|---|---|
ng new | Create a project |
ng generate / ng g | Scaffold code |
ng serve | Dev server |
ng build | Production build |
ng test | Unit tests |
ng e2e | End-to-end tests |
ng lint | Lint |
ng update | Upgrade |
ng add | Add a library |
ng config | Manage config |
ng version | Show versions |
ng help | Help |
Generate Schematics
| Command | Creates |
|---|---|
ng g component NAME | Component |
ng g service NAME | Service |
ng g directive NAME | Directive |
ng g pipe NAME | Pipe |
ng g guard NAME | Route guard |
ng g interface NAME | Interface |
ng g enum NAME | Enum |
ng g class NAME | Class |
ng g module NAME | Module |
ng g resolver NAME | Route resolver |
ng new Flags
| Flag | Effect |
|---|---|
--routing | Add routing |
--style=scss | Stylesheet format |
--ssr | Server-side rendering |
--standalone | Standalone components |
--skip-tests | No spec files |
--skip-git | No Git init |
--prefix=app | Selector prefix |
ng serve Flags
| Flag | Effect |
|---|---|
--port 4300 | Custom port |
--open | Open browser |
--host 0.0.0.0 | All interfaces |
--proxy-config FILE | API proxy |
--poll | File watcher polling |
ng build Flags
| Flag | Effect |
|---|---|
--configuration production | Production |
--base-href /app/ | Base URL |
--output-path dist/site | Output folder |
--source-map | Include source maps |
--stats-json | Emit stats file |
ng test Flags
| Flag | Effect |
|---|---|
--watch=false | Run once |
--code-coverage | Coverage report |
--browsers=ChromeHeadless | Headless browser |
--include=PATTERN | Filter specs |
Generate Flags
| Flag | Effect |
|---|---|
--flat | No folder |
--skip-tests | No spec file |
--inline-template | Inline HTML |
--inline-style | Inline CSS |
--standalone | Standalone |
--dry-run | Preview |
--change-detection=OnPush | OnPush strategy |
Workspace Commands
| Command | Purpose |
|---|---|
ng new --no-create-application | Workspace only |
ng generate application NAME | Add an app |
ng generate library NAME | Add a library |
ng build PROJECT | Build a specific project |
ng serve PROJECT | Serve 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
| Pitfall | Problem | Solution |
|---|---|---|
ng: command not found | CLI not on PATH | Reinstall or fix PATH |
| Wrong port in use | ng serve fails | --port 4300 |
| Hand-scaffolded files | Missing imports | Use ng generate |
| Deployed dev build | Large, slow | Use --configuration production |
ng update skips tests | Silent breakage | Run ng test after |
| Manual library setup | Config incomplete | Use ng add |
| Wrong schematic flags | Wrong shape | Check ng g c --help |
| Workspace project confusion | Wrong target | Use --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
| Command | Purpose |
|---|---|
ng new NAME | Create a project |
ng g c NAME | Generate component |
ng g s NAME | Generate service |
ng serve | Run dev server |
ng build | Production build |
ng test | Unit tests |
ng e2e | End-to-end tests |
ng add PKG | Add a library |
ng update | Upgrade Angular |
ng config | Manage configuration |
ng version | Show toolchain |
ng help | Help for any command |
Key takeaways:
- The Angular CLI (
ng) is the primary interface for all Angular tooling ng newcreates a full project — no manual setupng generate(orng g) scaffolds components, services, directives, and more with the correct wiring- Use
--dry-runto preview generation without writing files ng serveruns the dev server with hot reload athttp://localhost:4200- Use
--proxy-configto route API calls to a backend during development ng buildcompiles for production — tree-shaken, minified, hashedng testandng e2erun unit and end-to-end testsng addinstalls a library and configures it in one step — better than manualnpm installng updatehandles 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!