Angular on localhost:4200

http://localhost:4200

Angular development server runs on port 4200 by default when using ng serve. The server provides live reload and hot module replacement for efficient development.

→ Open localhost:4200

Install Angular CLI

# Install Angular CLI globally npm install -g @angular/cli # Verify installation ng version # Check for updates ng update

Create Angular Application

# Create new project ng new my-angular-app # Options during creation: # - Routing? Yes/No # - Stylesheet format? CSS/SCSS/SASS/LESS # Navigate into project cd my-angular-app # Start development server ng serve # Opens at http://localhost:4200

Angular CLI Commands

# Start dev server ng serve # Open browser automatically ng serve --open ng serve -o # Custom port ng serve --port 4300 # Production mode ng serve --configuration production # Host on network ng serve --host 0.0.0.0 # Disable live reload ng serve --live-reload false # Enable polling (for network drives) ng serve --poll=2000

Angular Project Structure

my-angular-app/ ├── src/ │ ├── app/ │ │ ├── app.component.ts # Root component │ │ ├── app.component.html # Template │ │ ├── app.component.css # Styles │ │ ├── app.component.spec.ts # Tests │ │ ├── app.module.ts # Root module │ │ └── app-routing.module.ts # Routes │ ├── assets/ # Static files │ ├── environments/ # Environment configs │ ├── index.html # Main HTML │ ├── main.ts # Entry point │ └── styles.css # Global styles ├── angular.json # Angular config ├── package.json # Dependencies ├── tsconfig.json # TypeScript config └── node_modules/

Generate Components

# Generate component ng generate component my-component ng g c my-component # Component with routing ng g c user --routing # Inline template and styles ng g c hero --inline-template --inline-style # Skip tests ng g c footer --skip-tests # Component in subfolder ng g c components/header

Generate Services

# Generate service ng generate service data ng g s data # Service in specific folder ng g s services/auth # Service without tests ng g s api --skip-tests

Generate Other Files

# Module ng g module shared # Module with routing ng g module products --routing # Directive ng g directive highlight # Pipe ng g pipe currency-format # Guard ng g guard auth # Interface ng g interface user # Enum ng g enum status # Class ng g class models/user

Example Component

// src/app/user/user.component.ts import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-user', templateUrl: './user.component.html', styleUrls: ['./user.component.css'] }) export class UserComponent implements OnInit { name: string = 'John Doe'; age: number = 30; users: string[] = ['Alice', 'Bob', 'Charlie']; constructor() { } ngOnInit(): void { console.log('Component initialized'); } onClick(): void { alert('Button clicked!'); } }
<!-- src/app/user/user.component.html --> <h2>User Component</h2> <p>Name: {{ name }}</p> <p>Age: {{ age }}</p> <button (click)="onClick()">Click Me</button> <ul> <li *ngFor="let user of users">{{ user }}</li> </ul>

Angular Routing

// src/app/app-routing.module.ts import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { HomeComponent } from './home/home.component'; import { AboutComponent } from './about/about.component'; import { UserComponent } from './user/user.component'; const routes: Routes = [ { path: '', component: HomeComponent }, { path: 'about', component: AboutComponent }, { path: 'user/:id', component: UserComponent }, { path: '**', redirectTo: '' } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { } // URLs: // http://localhost:4200/ // http://localhost:4200/about // http://localhost:4200/user/123

HTTP Service Example

// src/app/services/data.service.ts import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class DataService { private apiUrl = 'http://localhost:8000/api'; constructor(private http: HttpClient) { } getUsers(): Observable<any> { return this.http.get(`${this.apiUrl}/users`); } getUser(id: number): Observable<any> { return this.http.get(`${this.apiUrl}/users/${id}`); } createUser(user: any): Observable<any> { return this.http.post(`${this.apiUrl}/users`, user); } } // app.module.ts - Import HttpClientModule import { HttpClientModule } from '@angular/common/http'; @NgModule({ imports: [ BrowserModule, HttpClientModule ] })

Configure API Proxy

Create proxy.conf.json in project root:

{ "/api": { "target": "http://localhost:8000", "secure": false, "changeOrigin": true, "logLevel": "debug" } }

Update angular.json:

"architect": { "serve": { "options": { "proxyConfig": "proxy.conf.json" } } }

Or run with:

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

Change Angular Port

Command Line

ng serve --port 4300

angular.json

"architect": { "serve": { "options": { "port": 4300 } } }

package.json

{ "scripts": { "start": "ng serve --port 4300" } }

Angular Development Features

  • Live Reload - Automatic browser refresh on file changes
  • Hot Module Replacement - Update modules without full reload
  • TypeScript Compilation - Real-time type checking
  • AOT Compilation - Ahead-of-time compilation for production
  • Source Maps - Debug TypeScript in browser
  • Error Overlay - Clear error messages in browser
  • Angular DevTools - Browser extension for debugging

Build for Production

# Production build ng build --configuration production ng build --prod # Output directory: dist/my-angular-app/ # Build with source maps ng build --prod --source-map # Build with stats ng build --prod --stats-json # Serve production build locally npx http-server dist/my-angular-app -p 4200

Testing Commands

# Run unit tests (Karma) ng test # Run tests once ng test --watch=false # Run with code coverage ng test --code-coverage # End-to-end tests (Cypress/Protractor) ng e2e # Lint code ng lint

Fix "Angular Not Working"

Issue: Port 4200 already in use

# Find what's using port 4200 # Windows netstat -ano | findstr :4200 # Linux/Mac lsof -i :4200 # Use different port ng serve --port 4300

Issue: Module not found

# Clear node_modules and reinstall rm -rf node_modules package-lock.json npm install # Or npm ci

Issue: Can't bind to 'ngModel'

// Import FormsModule in app.module.ts import { FormsModule } from '@angular/forms'; @NgModule({ imports: [ BrowserModule, FormsModule ] })

Issue: Live reload not working

  • Check file is saving (Ctrl+S)
  • Verify file is in src/ directory
  • Restart ng serve
  • Clear browser cache
  • Try polling: ng serve --poll=2000

Angular vs React vs Vue

Feature Angular React Vue
Default Port 4200 3000 8080/5173
Language TypeScript JavaScript/TypeScript JavaScript
Type Full Framework Library Framework
CLI Angular CLI Create React App Vue CLI/Vite
Best Practice: Use Angular CLI for all project operations (generate, build, test) rather than manual file creation. The CLI ensures proper structure and configuration.

Frequently Asked Questions

What port does Angular use?

Angular development server uses port 4200 by default. Change it with ng serve --port or in angular.json configuration.

Do I need TypeScript for Angular?

Yes, Angular is built with TypeScript. All Angular projects use TypeScript for components, services, and modules.

Can I use Angular without CLI?

While possible, it's not recommended. Angular CLI handles complex build configuration, development server, and code generation efficiently.

How do I deploy Angular from localhost?

Run ng build --prod, then upload the dist/ folder contents to your web server. Configure server to redirect all routes to index.html for proper routing.

Related Resources