Phase 2 — Angular Fundamentals

Chapter 1 — What is Angular and How Does it Think?


1.1 — What is Angular?

Angular is a framework for building web applications. A framework is basically a set of tools, rules, and pre-written code that helps you build things faster and in a more organized way.

Think of it like this. If you wanted to build a house, you could gather all the raw materials yourself — wood, bricks, cement, tools — and figure everything out from scratch. That would take forever. OR you could use a construction kit that already has everything organized, pre-measured, and ready to assemble. Angular is that construction kit for web apps.

Without Angular, building a complex web app in plain HTML, CSS, and JavaScript means you have to manually manage everything — updating the page when data changes, organizing your code, handling navigation between pages. It gets messy very fast.

Angular handles all of that for you. You focus on building features. Angular handles the rest.


1.2 — The Problem Angular Solves — Traditional Websites vs Angular

To truly understand why Angular exists, you need to understand the problem it solves.

On a traditional website, every time you click a link, here is what happens:

Your browser sends a request to the server saying "hey, I want the About page." The server prepares a brand new HTML file for the About page and sends it back. Your browser completely throws away the current page and renders the new one from scratch. You see a white flash. Everything resets. Your scroll position is gone. Any data you had on the previous page is gone.

Now multiply this by every single click. Every navigation. Every page visit. This is slow and feels clunky.

Angular solves this completely with a concept called a Single Page Application, or SPA.

Here is how it works with Angular:

When you first open an Angular app, the browser loads one single HTML file — just once. After that, Angular completely takes over. When you click a link, Angular does NOT ask the server for a new page. Instead, it dynamically swaps out pieces of the screen — showing some components, hiding others — right there in the browser. The URL in your address bar changes, the content on screen changes, but the page never actually reloads.

This is why Angular apps feel fast and smooth. There is no round trip to the server. No white flash. No state reset. Everything happens instantly in the browser.


1.3 — The Most Important Concept — Think in Components

This is the single most important mental shift you need to make when learning Angular. Stop thinking about pages. Start thinking about components.

A component is a self-contained, reusable piece of your UI. It has its own HTML structure, its own CSS styles, and its own TypeScript logic. It is like a LEGO block for your web app.

Look at any website and you can immediately identify the components:

┌──────────────────────────────────────┐
│           NavbarComponent            │  ← handles logo, menu links
├──────────────────────────────────────┤
│                                      │
│           HeroComponent              │  ← handles headline, CTA button
│                                      │
├──────────────────────────────────────┤
│                                      │
│          SkillsComponent             │  ← handles section title
│  ┌──────────┐  ┌──────────┐          │
│  │ SkillCard│  │ SkillCard│  ...     │  ← each card is its own component
│  └──────────┘  └──────────┘          │
│                                      │
├──────────────────────────────────────┤
│           FooterComponent            │  ← handles footer text
└──────────────────────────────────────┘

Every section is a component. And components can live inside other components — the Skills section is a component, and inside it, each individual skill card is also a component.

This nesting of components inside components is called a component tree. At the very top of this tree sits one root component. In Angular that root component is called App. Every other component in your entire application lives somewhere inside it.

Why is this approach powerful? Because each component is independent. You can reuse the same SkillCard component ten times on the page. Each instance manages itself. If you update the SkillCard component, every instance automatically gets the update. You build once, use everywhere.


1.4 — How Angular Components Work — The Big Picture

Every Angular component has exactly three parts working together:

The TypeScript file is the brain. This is where your data and logic live. What is the user's name? What items are in the list? What should happen when a button is clicked? All of that lives in the TypeScript class.

The HTML file is the face. This is the template — what the component actually looks like on screen. It uses the data from the TypeScript file to display things dynamically.

The CSS file is the clothing. Styles that only apply to this component and nothing else in the app.

These three files together make one complete component. They always work as a team.


Chapter 2 — Setting Up Angular


2.1 — Installing Node.js

Before you can use Angular, you need Node.js installed on your computer.

Node.js is a JavaScript runtime — it lets JavaScript run outside the browser, directly on your computer. Angular's tools need this to work.

Go to nodejs.org and download the LTS version. LTS stands for Long Term Support. It is the stable, tested, recommended version. Do not download the "Current" version — that one may have experimental features that are unstable.

After the installation finishes, open your terminal (on Windows: search for "Command Prompt" or "PowerShell") and run:

node --version

You should see a version number printed like v22.17.1. Then run:

npm --version

You should see something like 11.12.1.

npm stands for Node Package Manager. It came bundled automatically with Node.js. It is the tool you use to install Angular and every other JavaScript library throughout this course. Think of npm like an app store for JavaScript packages.

If both commands print version numbers, your Node.js installation is working perfectly.


2.2 — Installing the Angular CLI

CLI stands for Command Line Interface. The Angular CLI is a tool you install once and use throughout your entire Angular career.

What does the CLI do? It handles the boring, repetitive work for you. Instead of manually creating files, writing boilerplate code, and configuring everything yourself — you type one short command and the CLI does it all. Creating a new project, generating a component, running a development server, building for production — all of this is one command away.

Install it by running this in your terminal:

npm install -g @angular/cli

The -g flag means global. This installs the CLI on your entire computer so you can use it in any project, anywhere, anytime.

After installation completes, verify it worked:

ng version

This will print out Angular CLI version information. ng is the command you type for everything Angular related. You will type ng hundreds of times throughout this course.


2.3 — Creating Your First Angular Project

Navigate to wherever you keep your coding projects in the terminal. For example:

cd Desktop

Now create a new Angular project:

ng new my-angular-app

The CLI will ask you two questions interactively.

First question — Which stylesheet format would you like to use?

You will see options like CSS, SCSS, SASS, LESS. Use your arrow keys to highlight CSS and press Enter. CSS is the standard and it is what we use throughout this course.

Second question — Do you want to enable Server-Side Rendering (SSR)?

Type N and press Enter. Server-Side Rendering is an advanced topic we do not need right now.

After you answer both questions, the CLI gets to work. It creates the project folder, generates all the necessary files, and automatically runs npm install to download all the packages Angular needs. This step takes a minute or two because it is downloading packages from the internet.

Once it finishes, navigate into your new project:

cd my-angular-app

Now start the development server:

ng serve

Open your browser and go to:

http://localhost:4200

You will see the Angular default welcome page. Your app is running.

Here is something really useful about ng serve — it watches your files. Every single time you save any change to any file in your project, it automatically recompiles the code and refreshes the browser. You never need to manually refresh while developing. Just save and see changes instantly.

To stop the server at any time, press Ctrl + C in the terminal.


Chapter 3 — Understanding Your Project Files


Open your project folder in VS Code. You will see this structure:

my-angular-app/
│
├── public/                   ← your images, fonts, icons go here
│
├── src/                      ← all your app code lives here
│   ├── app/
│   │   ├── app.ts            ← root component logic
│   │   ├── app.html          ← root component template
│   │   ├── app.css           ← root component styles
│   │   ├── app.spec.ts       ← root component tests
│   │   ├── app.config.ts     ← app-wide configuration
│   │   └── app.routes.ts     ← all route definitions
│   │
│   ├── index.html            ← the ONE html file
│   ├── main.ts               ← entry point, app starts here
│   └── styles.css            ← global styles
│
├── angular.json              ← Angular project configuration
├── package.json              ← project dependencies
├── tsconfig.json             ← base TypeScript config
├── tsconfig.app.json         ← TypeScript config for app
└── tsconfig.spec.json        ← TypeScript config for tests

Two things to notice immediately.

The public/ folder is outside src/. It sits at the root level of your project. Any images, fonts, or icons you want to use in your app go inside this folder.

There is no app.module.ts file anywhere. Modern Angular does not use module files. Everything works without them.

Now let's go through every important file one by one and understand exactly what each one does and why it exists.


3.1 — index.html — The One HTML File

Open src/index.html:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>MyAngularApp</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
  <app-root></app-root>
</body>
</html>

The first thing you notice is that this is a completely normal HTML file — except for one tag: <app-root></app-root>.

That tag is not a standard HTML element. Your browser has no idea what <app-root> means. But Angular does. <app-root> is the selector for your root App component. When Angular starts, it finds this tag and replaces it with your entire application.

Everything your user ever sees — every component, every page, every button — gets rendered inside that one <app-root> tag.

This file stays exactly as it is throughout your entire project. You will almost never touch it.

The <base href="/"> line is required for Angular's router to work correctly. It tells the browser that all URLs in this app start from the root domain. Without this line, navigation would break.


3.2 — main.ts — Where Your App Starts

Open src/main.ts:

import { bootstrapApplication } from '@angular/platform-browser';
import { appConfig } from './app/app.config';
import { App } from './app/app';

bootstrapApplication(App, appConfig)
  .catch((err) => console.error(err));

This is the entry point of your application. It is the very first TypeScript file that runs when someone opens your app.

bootstrapApplication is a function from Angular that starts your application. You pass it two things — the root component (App) and the configuration object (appConfig).

When this function runs, Angular boots up, reads the configuration, finds the App component, matches its selector app-root to the <app-root> tag in index.html, and renders your entire app inside it.

The .catch() at the end is just basic error handling. If something goes wrong during startup, it logs the error to the browser console.

You will rarely edit this file. Its job is simple — start the app.


3.3 — app.config.ts — The App's Configuration Center

Open src/app/app.config.ts:

import { ApplicationConfig, provideZoneChangeDetection } from '@angular/core';
import { provideRouter } from '@angular/router';
import { routes } from './app.routes';

export const appConfig: ApplicationConfig = {
  providers: [
    provideZoneChangeDetection({ eventCoalescing: true }),
    provideRouter(routes)
  ]
};

This file is passed to bootstrapApplication in main.ts. It tells Angular how to configure the application at the global level.

The providers array is the key part. Whatever you put in this array becomes available throughout your entire application.

provideRouter(routes) sets up Angular's routing system using the routes you will define in app.routes.ts. Without this line, navigation between pages would not work.

provideZoneChangeDetection({ eventCoalescing: true }) is a performance setting. It tells Angular to batch multiple browser events together before checking what needs to update on screen. This reduces unnecessary work. You can leave this as it is — it is already the correct setting.

As you progress through this course, you will add more things to this providers array. For example, when you start making API calls in Phase 8, you will add provideHttpClient() here. When you add animations in Phase 10, you will add provideAnimations(). Everything that needs to work app-wide goes here.


3.4 — app.routes.ts — Your App's Navigation Map

Open src/app/app.routes.ts:

import { Routes } from '@angular/router';

export const routes: Routes = [];

This file is a simple TypeScript file that exports an array of route objects. Each route object maps a URL path to a component. Right now the array is empty because we have not created any pages yet.

When we reach Phase 6, this file will look something like this:

export const routes: Routes = [
  { path: '', component: Home },
  { path: 'about', component: About },
  { path: 'projects', component: Projects }
];

This means: when the URL is /, show the Home component. When the URL is /about, show the About component. And so on.

For now just know this file exists and this is where all your app's navigation is defined.


3.5 — app.ts — The Root Component

Open src/app/app.ts. This is the most important file to understand right now:

import { Component, signal } from '@angular/core';
import { RouterOutlet } from '@angular/router';

@Component({
  selector: 'app-root',
  imports: [RouterOutlet],
  templateUrl: './app.html',
  styleUrl: './app.css'
})
export class App {
  protected readonly title = signal('my-angular-app');
}

Let's go through every single part carefully because you will write code like this constantly.


The import statement at the top

import { Component, signal } from '@angular/core';
import { RouterOutlet } from '@angular/router';

Just like in regular TypeScript, before you can use something, you import it. Component is the decorator that tells Angular this class is a component. signal is Angular's reactive value system — more on this in a moment. RouterOutlet is imported because the template uses <router-outlet>.


The @Component decorator

@Component({
  selector: 'app-root',
  imports: [RouterOutlet],
  templateUrl: './app.html',
  styleUrl: './app.css'
})

A decorator is a special piece of code that starts with @ and sits right above a class. It adds information and behavior to that class without changing the class itself.

The @Component decorator is what tells Angular "hey, this TypeScript class is not just any class — it is a component." Without this decorator, Angular would completely ignore the class.

Inside the decorator, you pass a configuration object:

selector: 'app-root' — this is the custom HTML tag name for this component. Anywhere you write <app-root> in an HTML file, Angular will render this component there. Every component selector starts with app- by convention.

imports: [RouterOutlet] — this is the list of everything your template uses. RouterOutlet is here because app.html contains <router-outlet>. This is the most important concept in Angular — if you use something in the template, you must import it here. We will talk about this deeply in the next chapter.

templateUrl: './app.html' — the path to this component's HTML template file. Angular reads this file and uses it as the component's visual structure.

styleUrl: './app.css' — the path to this component's CSS file. The important thing to understand is that these styles are scoped — they only affect this component, not any other component in the app. You can use the same class name like .title in ten different components and they will never conflict with each other.


The class

export class App {
  protected readonly title = signal('my-angular-app');
}

This is a regular TypeScript class. The class name is App — that is the name Angular uses to identify this component in TypeScript code.

The title property is interesting. It is a signal — Angular's modern way to hold a reactive value.


Understanding Signals

A signal is a container that holds a value and notifies Angular automatically when that value changes.

When you use a regular TypeScript property, Angular has to constantly check all properties to see if anything changed. With a signal, Angular knows exactly which value changed and only updates the specific parts of the screen that depend on that value. This makes your app more efficient.

You create a signal by calling the signal() function with an initial value:

title = signal('my-angular-app');
count = signal(0);
isLoggedIn = signal(false);
userName = signal('Rahul');

To read a signal's value inside a template, you call it like a function — with parentheses ():

<h1>{{ title() }}</h1>
<p>Count is: {{ count() }}</p>

To update a signal's value in TypeScript, you use .set():

this.title.set('Welcome!');
this.count.set(10);
this.isLoggedIn.set(true);

To update a signal based on its current value, you use .update():

this.count.update(currentValue => currentValue + 1);
// If count was 5, it is now 6

That is all you need to know about signals for now. We go deep on them in Phase 10. For now just remember: when you use a signal in a template, add () after its name.


3.6 — app.html — The Root Template

Open src/app/app.html. It contains a large default welcome page. Delete all of it and replace with this:

<h1>Hello Angular!</h1>
<p>{{ title() }}</p>
<router-outlet></router-outlet>

Notice {{ title() }} — the double curly braces {{ }} is called interpolation. It is how you display a TypeScript value in your HTML. Since title is a signal, you add () to read its value.

<router-outlet> is a placeholder. When you set up routing in Phase 6, page components will appear in this exact spot when the user navigates. Think of it as a blank TV screen — routes will "play" on this screen.

Save the file and check localhost:4200. Your browser instantly refreshes and shows your new content.


3.7 — styles.css — Global Styles

Open src/styles.css. This is the one place where your styles affect the entire application. Every component will be affected by what you put here.

Use this file for:

  • Global CSS resets
  • Font family settings on the body
  • Global color variables
  • Any style that should apply everywhere
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  background-color: #f5f5f5;
  color: #333;
}

Every component has its own CSS file for styles that are specific to that component only. styles.css is the only one that is truly global.


3.8 — public/ Folder — Static Files

The public/ folder lives outside src/ at the root of your project. This is where you put static files that your app needs — images, custom fonts, icons, and any other files that don't change.

If you have a profile photo for your portfolio, you put it inside public/. Let's say you create a folder inside public/ called images and put photo.jpg inside it:

public/
└── images/
    └── photo.jpg

To use it in any template:

<img src="/images/photo.jpg" alt="My photo">

You reference files from public/ with a leading /. Angular serves everything inside public/ directly at the root of your app's URL.


3.9 — angular.json — Project Configuration

This is Angular's master configuration file. It is automatically generated and you rarely need to edit it manually. But understanding what it does is useful.

It tells Angular things like: where your source files are, where to put the production build output, which global stylesheets to load, which assets to include.

The one time you will manually edit it as a beginner is when you want to add a global CSS library like Bootstrap. You would add the Bootstrap CSS file path to the styles array:

"styles": [
  "src/styles.css",
  "node_modules/bootstrap/dist/css/bootstrap.min.css"
]

Other than that, leave this file as it is.


3.10 — package.json — Your Project's Dependency List

{
  "scripts": {
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test"
  },
  "dependencies": {
    "@angular/core": "^21.2.0",
    "@angular/common": "^21.2.0",
    "@angular/router": "^21.2.0"
  },
  "devDependencies": {
    "@angular/cli": "^21.2.5",
    "typescript": "~5.9.2",
    "vitest": "^4.0.8"
  }
}

dependencies — packages your app needs to actually run. These get included in your production build.

devDependencies — packages only needed during development, like the CLI and the test runner (Vitest). These are NOT included in the production build. Users downloading your app don't need these.

scripts — shortcuts for common tasks. When you type npm start in the terminal, it runs ng serve. When you type npm run build, it runs ng build. These are just convenience shortcuts.


3.11 — tsconfig Files

You have three TypeScript configuration files:

tsconfig.json is the base configuration that the other two extend. It contains settings shared by everything.

tsconfig.app.json is the TypeScript configuration specifically for building your application.

tsconfig.spec.json is the TypeScript configuration specifically for running your tests.

The most important setting in tsconfig.json is "strict": true. This enables strict TypeScript type checking. It catches more bugs before your code even runs. Always keep this set to true. If TypeScript gives you an error, fix the code — do not disable strict mode to silence the error.


Chapter 4 — Components in Depth


4.1 — Generating a Component

The Angular CLI generates components for you with a single command:

ng generate component navbar

The shorthand for the same command:

ng g c navbar

When you run this inside your Angular project, the CLI creates a new folder called navbar inside src/app/ and generates these files:

src/app/navbar/
├── navbar.ts
├── navbar.html
├── navbar.css
└── navbar.spec.ts

The naming in Angular is clean and simple. The files are just navbar.ts, navbar.html, and navbar.css. No extra words in the file names. The .spec.ts file is for writing tests — we cover tests in Phase 10.


4.2 — What the Generated Component Looks Like

Open the generated navbar.ts:

import { Component } from '@angular/core';

@Component({
  selector: 'app-navbar',
  imports: [],
  templateUrl: './navbar.html',
  styleUrl: './navbar.css'
})
export class Navbar {

}

This is clean and minimal. Let's look at what each part means.

The selector is 'app-navbar'. This is the custom HTML tag you will use to place this component anywhere in your app. Want the navbar to appear somewhere? Write <app-navbar></app-navbar> in any template.

The imports array is empty. You add things here as your template needs them. We will talk about what to add here very shortly.

The class name is Navbar. Not NavbarComponent — just Navbar. Angular uses this class name when you import the component in TypeScript.

The template file is navbar.html and the style file is navbar.css. Angular automatically points to these files correctly.


4.3 — Adding Data to a Component

A component's TypeScript class is where all your data and logic lives. Let's add some real content to the Navbar component:

navbar.ts:

import { Component } from '@angular/core';

@Component({
  selector: 'app-navbar',
  imports: [],
  templateUrl: './navbar.html',
  styleUrl: './navbar.css'
})
export class Navbar {
  siteName: string = 'MyPortfolio';
  navLinks: string[] = ['Home', 'About', 'Projects', 'Contact'];
}

You just added two properties to the class. siteName is a string that holds the website name. navLinks is an array of strings holding the navigation link labels.

Now let's display this data in the template.


4.4 — Displaying Data in the Template

Open navbar.html and replace the placeholder content:

<nav>
  <div class="logo">{{ siteName }}</div>
  <ul>
    @for (link of navLinks; track link) {
      <li><a href="#">{{ link }}</a></li>
    }
  </ul>
</nav>

Two important things happening here.

{{ siteName }} — the double curly braces read the siteName property from the TypeScript class and display its value in the HTML. This is called interpolation. Whatever value siteName holds in TypeScript will appear here on screen.

@for (link of navLinks; track link) — this is Angular's built-in loop syntax. It loops through every item in the navLinks array and renders the HTML inside the block once for each item. Since navLinks has 4 items, Angular renders 4 <li> elements automatically.

The track link part tells Angular to use the link value itself to uniquely identify each item. This helps Angular update the list efficiently when items change.

We cover @for, @if, and all the template syntax deeply in Phase 4. For now just know that @for loops and {{ }} displays data.


4.5 — Using One Component Inside Another

This is the core workflow in Angular. You build small components and then compose them together inside larger ones.

Let's say you want to use Navbar inside your root App component. Two steps.

Step 1 — Import the component in app.ts:

import { Component } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import { Navbar } from './navbar/navbar';

@Component({
  selector: 'app-root',
  imports: [
    RouterOutlet,
    Navbar
  ],
  templateUrl: './app.html',
  styleUrl: './app.css'
})
export class App { }

You imported Navbar from its file path './navbar/navbar' — that is the folder name followed by the file name, without the .ts extension. Then you added it to the imports array inside @Component.

Step 2 — Use its selector as a tag in app.html:

<app-navbar></app-navbar>
<router-outlet></router-outlet>

Save both files and check localhost:4200. Your Navbar component is now rendered at the top of the page.

This is the complete workflow:

  1. Generate a component with ng g c
  2. Import it in the parent's imports array
  3. Use its selector as an HTML tag in the parent's template

4.6 — The Golden Rule of Angular

If you use something in your template, it must be in the component's imports array.

This is the most important rule to remember. Let's break it down with examples.

If your template uses another component:

// In the template: <app-navbar></app-navbar>
// In the imports array:
imports: [Navbar]

If your template uses Angular's @for loop with a pipe:

// In the template: {{ price | currency }}
// In the imports array:
imports: [CurrencyPipe]

If your template uses router navigation:

// In the template: <a routerLink="/about">About</a>
// In the imports array:
imports: [RouterLink]

If you forget to add something to imports, Angular will throw a clear error in the browser console telling you exactly what is missing. It will say something like 'Navbar' is not a known element. That error always means the same thing — go add it to the imports array.


Chapter 5 — How Angular Starts From Zero to Running App


Let's trace through exactly what happens the moment someone opens your Angular app in the browser. Understanding this sequence means when something goes wrong during startup, you know exactly where to look.

Step 1 — The browser requests the page

The user opens localhost:4200. The dev server receives this request and responds with index.html.

Step 2 — The browser reads index.html

The browser starts reading index.html. It sees <app-root></app-root> in the body. It has absolutely no idea what this tag means. It continues reading.

Step 3 — Angular's JavaScript loads

The Angular CLI automatically adds <script> tags to index.html during the build. The browser downloads these JavaScript files — they contain your entire application compiled into JavaScript.

Step 4 — main.ts runs

The JavaScript executes and main.ts runs first. This line executes:

bootstrapApplication(App, appConfig)

This is the ignition switch. Angular starts up.

Step 5 — appConfig is processed

Angular reads appConfig and processes all the providers. The router is initialized with your routes from app.routes.ts. Any other app-wide setup happens here.

Step 6 — The App component renders

Angular looks at the App component's selector: 'app-root'. It searches index.html for a matching element. It finds <app-root></app-root> and replaces it with the contents of app.html.

Step 7 — Child components render

Angular processes app.html. It finds <app-navbar>. Angular searches the App component's imports array, finds the Navbar component, and renders navbar.html in that spot. This happens for every child component in every template.

Step 8 — The app is live

The complete component tree is rendered on screen. Angular is now watching for user interactions — button clicks, form inputs, navigation — and will update the screen reactively as things change.

Here is the complete flow in one diagram:

User opens localhost:4200
          ↓
Server sends index.html
          ↓
Browser downloads Angular JS bundles
          ↓
main.ts runs
          ↓
bootstrapApplication(App, appConfig)
          ↓
appConfig processed — router set up
          ↓
App component's selector 'app-root'
matched in index.html
app.html rendered inside it
          ↓
Child components rendered
(each one matched from imports array)
          ↓
App is fully live ✓

Chapter 6 — Angular CLI Commands


The Angular CLI is your daily tool throughout this course. Here are all the commands you will use, explained clearly.


Creating a new project

ng new project-name

This creates a brand new Angular project from scratch. The CLI asks you about stylesheet format and SSR, then generates everything automatically.


Starting the development server

ng serve

This starts the live development server at localhost:4200. It watches your files and auto-refreshes on save. You keep this running while you develop.

ng serve -o

The -o flag stands for --open. It starts the server AND automatically opens your browser. Saves you one step.

ng serve --port 3000

Use a different port if 4200 is already occupied by something else.


Generating a component

ng generate component header
ng g c header

Both commands do the same thing. The second is just shorter. This creates a new folder with header.ts, header.html, header.css, and header.spec.ts.

ng g c header --skip-tests

Adds --skip-tests to skip generating the .spec.ts test file. We will use this while learning to keep things clean.

ng g c products/product-card

Generates a product-card component inside a products subfolder. This creates src/app/products/product-card/.

ng g c header --flat

Generates the component files without creating a new subfolder. The files go directly in whatever folder you are in.


Generating other things

ng g s user          ← generate a service
ng g p truncate      ← generate a pipe
ng g d highlight     ← generate a directive
ng g guard auth      ← generate a route guard

We will use all of these in later phases. Just know these commands exist.


Building for production

ng build

Compiles your app into optimized JavaScript files ready to deploy. The output goes into a dist/ folder. These files are what you upload to a web server.

ng build --configuration=production

The full production build with all optimizations — minification, tree-shaking (removing unused code), and everything else that makes your app as small and fast as possible.


Other useful commands

ng version

Shows you the exact versions of Angular, CLI, Node.js, and TypeScript installed. Useful for debugging compatibility issues.

ng test

Runs your test suite using Vitest.

ng lint

Checks your code for quality issues and style problems.


Chapter 7 — Building a Real Portfolio App


Now we put everything from this phase into practice. We will build a Developer Portfolio Page with four components — Navbar, Hero, Skills, and Footer. This is a real Angular project using everything you just learned.


Step 1 — Create the project

Open your terminal and run:

ng new portfolio-app --style=css

When asked about SSR, type N. Wait for the setup to complete, then:

cd portfolio-app

Step 2 — Generate the four components

ng g c navbar --skip-tests
ng g c hero --skip-tests
ng g c skills --skip-tests
ng g c footer --skip-tests

After running all four commands, your src/app/ folder looks like this:

src/app/
├── navbar/
│   ├── navbar.ts
│   ├── navbar.html
│   └── navbar.css
├── hero/
│   ├── hero.ts
│   ├── hero.html
│   └── hero.css
├── skills/
│   ├── skills.ts
│   ├── skills.html
│   └── skills.css
├── footer/
│   ├── footer.ts
│   ├── footer.html
│   └── footer.css
├── app.ts
├── app.html
├── app.css
├── app.config.ts
└── app.routes.ts

Step 3 — Build the Navbar Component

src/app/navbar/navbar.ts:

import { Component } from '@angular/core';

@Component({
  selector: 'app-navbar',
  imports: [],
  templateUrl: './navbar.html',
  styleUrl: './navbar.css'
})
export class Navbar {
  siteName: string = 'DevPortfolio';
  navLinks: string[] = ['Home', 'About', 'Projects', 'Contact'];
}

src/app/navbar/navbar.html:

<nav>
  <div class="logo">{{ siteName }}</div>
  <ul>
    @for (link of navLinks; track link) {
      <li><a href="#">{{ link }}</a></li>
    }
  </ul>
</nav>

src/app/navbar/navbar.css:

nav {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 18px 48px;
  background: #0f0f23;
}

.logo {
  font-size: 22px;
  font-weight: 700;
  color: #64ffda;
  letter-spacing: 1px;
}

ul {
  list-style: none;
  display: flex;
  gap: 32px;
  margin: 0;
  padding: 0;
}

a {
  color: #ccd6f6;
  text-decoration: none;
  font-size: 15px;
  transition: color 0.2s;
}

a:hover {
  color: #64ffda;
}

Step 4 — Build the Hero Component

src/app/hero/hero.ts:

import { Component } from '@angular/core';

@Component({
  selector: 'app-hero',
  imports: [],
  templateUrl: './hero.html',
  styleUrl: './hero.css'
})
export class Hero {
  greeting: string = "Hi, I'm";
  name: string = 'Rahul Sharma';
  role: string = 'Angular Developer';
  description: string = 'I build fast, scalable web apps with modern Angular and TypeScript.';
  yearsExp: number = 3;
  projectsBuilt: number = 20;
  happyClients: number = 15;
}

src/app/hero/hero.html:

<section class="hero">
  <p class="greeting">{{ greeting }}</p>
  <h1>{{ name }}</h1>
  <h2>{{ role }}</h2>
  <p class="description">{{ description }}</p>

  <div class="stats">
    <div class="stat">
      <span class="number">{{ yearsExp }}+</span>
      <span class="label">Years Experience</span>
    </div>
    <div class="stat">
      <span class="number">{{ projectsBuilt }}+</span>
      <span class="label">Projects Built</span>
    </div>
    <div class="stat">
      <span class="number">{{ happyClients }}+</span>
      <span class="label">Happy Clients</span>
    </div>
  </div>

  <button class="cta">View My Work</button>
</section>

src/app/hero/hero.css:

.hero {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 90vh;
  text-align: center;
  padding: 40px 24px;
  background: #0a192f;
}

.greeting {
  font-size: 18px;
  color: #64ffda;
  margin-bottom: 8px;
}

h1 {
  font-size: 60px;
  font-weight: 700;
  color: #ccd6f6;
  margin-bottom: 8px;
}

h2 {
  font-size: 30px;
  font-weight: 400;
  color: #8892b0;
  margin-bottom: 20px;
}

.description {
  max-width: 560px;
  line-height: 1.8;
  color: #8892b0;
  font-size: 16px;
}

.stats {
  display: flex;
  gap: 56px;
  margin: 48px 0;
}

.stat {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 6px;
}

.number {
  font-size: 40px;
  font-weight: 700;
  color: #64ffda;
}

.label {
  font-size: 13px;
  color: #8892b0;
  text-transform: uppercase;
  letter-spacing: 1px;
}

.cta {
  padding: 14px 40px;
  background: transparent;
  color: #64ffda;
  border: 2px solid #64ffda;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
  letter-spacing: 1px;
  transition: background 0.2s;
}

.cta:hover {
  background: rgba(100, 255, 218, 0.1);
}

Step 5 — Build the Skills Component

src/app/skills/skills.ts:

import { Component } from '@angular/core';

@Component({
  selector: 'app-skills',
  imports: [],
  templateUrl: './skills.html',
  styleUrl: './skills.css'
})
export class Skills {
  sectionTitle: string = 'Skills & Technologies';

  skills = [
    { name: 'Angular', level: 90 },
    { name: 'TypeScript', level: 88 },
    { name: 'RxJS', level: 78 },
    { name: 'HTML & CSS', level: 92 },
    { name: 'Node.js', level: 72 },
    { name: 'Git', level: 85 }
  ];
}

src/app/skills/skills.html:

<section class="skills">
  <h2>{{ sectionTitle }}</h2>

  <div class="grid">
    @for (skill of skills; track skill.name) {
      <div class="card">
        <div class="card-header">
          <span class="skill-name">{{ skill.name }}</span>
          <span class="skill-level">{{ skill.level }}%</span>
        </div>
        <div class="bar-track">
          <div class="bar-fill" [style.width.%]="skill.level"></div>
        </div>
      </div>
    }
  </div>
</section>

src/app/skills/skills.css:

.skills {
  padding: 80px 48px;
  background: #112240;
  text-align: center;
}

h2 {
  font-size: 38px;
  color: #ccd6f6;
  margin-bottom: 52px;
}

.grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 24px;
  max-width: 860px;
  margin: 0 auto;
}

.card {
  background: #0a192f;
  padding: 22px 26px;
  border-radius: 8px;
  border: 1px solid #233554;
}

.card-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 12px;
}

.skill-name {
  color: #ccd6f6;
  font-size: 15px;
  font-weight: 600;
}

.skill-level {
  color: #64ffda;
  font-size: 14px;
}

.bar-track {
  height: 6px;
  background: #233554;
  border-radius: 3px;
  overflow: hidden;
}

.bar-fill {
  height: 100%;
  background: linear-gradient(90deg, #64ffda, #0070f3);
  border-radius: 3px;
}

Step 6 — Build the Footer Component

src/app/footer/footer.ts:

import { Component } from '@angular/core';

@Component({
  selector: 'app-footer',
  imports: [],
  templateUrl: './footer.html',
  styleUrl: './footer.css'
})
export class Footer {
  year: number = new Date().getFullYear();
  name: string = 'Rahul Sharma';
}

src/app/footer/footer.html:

<footer>
  <p>Designed & Built by <span class="highlight">{{ name }}</span></p>
  <p class="copy">© {{ year }} — All rights reserved</p>
</footer>

src/app/footer/footer.css:

footer {
  text-align: center;
  padding: 36px;
  background: #0a192f;
  border-top: 1px solid #233554;
}

p {
  color: #8892b0;
  font-size: 14px;
  margin: 4px 0;
}

.highlight {
  color: #64ffda;
}

.copy {
  font-size: 12px;
  margin-top: 8px;
}

Step 7 — Connect All Four Components in app.ts

Now wire everything together. Open src/app/app.ts and replace its entire contents:

import { Component } from '@angular/core';
import { Navbar } from './navbar/navbar';
import { Hero } from './hero/hero';
import { Skills } from './skills/skills';
import { Footer } from './footer/footer';

@Component({
  selector: 'app-root',
  imports: [
    Navbar,
    Hero,
    Skills,
    Footer
  ],
  templateUrl: './app.html',
  styleUrl: './app.css'
})
export class App { }

Open src/app/app.html and replace everything with:

<app-navbar></app-navbar>
<app-hero></app-hero>
<app-skills></app-skills>
<app-footer></app-footer>

Open src/styles.css and replace everything with:

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

Now run ng serve -o in the terminal. Your complete portfolio page will open in the browser.


Understanding What Just Happened

Let's trace through the complete flow of this project to make sure everything clicks.

When the browser opened localhost:4200, the server sent index.html. Angular loaded and ran main.ts, which called bootstrapApplication(App, appConfig).

Angular looked at the App component and found its selector app-root. It matched this to <app-root> in index.html and rendered app.html inside it.

app.html had four tags — <app-navbar>, <app-hero>, <app-skills>, <app-footer>. Angular looked in App's imports array and found Navbar, Hero, Skills, and Footer. It rendered each one in order.

The Navbar component had a siteName string and a navLinks array in its class. The navbar.html template displayed siteName with {{ siteName }} and looped through navLinks with @for to generate the menu items.

The Skills component had a skills array in its class. The skills.html template used @for to loop through the array and render one card per skill, with a progress bar using [style.width.%]="skill.level" to dynamically set the width.

Each component managed itself completely independently. No component knew anything about the others except that the root App imported all of them.

This is the beauty of component-based architecture. Everything is organized, independent, and reusable.


Phase 2 — Complete Summary

You have covered a lot of ground in this phase. Here is everything you learned:

Single Page Application — Angular loads one HTML file once. All navigation after that is Angular swapping components on screen. No full page reloads, no white flashes, no state loss.

Component tree — Your entire app is a tree of components. The root App component sits at the top. Every other component lives somewhere inside it.

What a component is — Three files working together. A TypeScript file for data and logic, an HTML file for the template, and a CSS file for scoped styles.

Angular project filesindex.html holds <app-root>. main.ts starts the app. app.config.ts holds app-wide configuration. app.routes.ts holds navigation routes. styles.css holds global styles. public/ holds static assets.

Signals — A reactive way to hold values. Create with signal(), read in templates with (), update with .set().

No module files — Angular does not use app.module.ts. Components are standalone and manage their own dependencies.

The golden rule — If you use something in a template, import it in the component's imports array.

Angular file naming — Files are navbar.ts, navbar.html, navbar.css. Class names are Navbar, Hero, Skills — clean and simple, no extra words.

The startup flowmain.tsbootstrapApplicationappConfigApp renders → children render → app is live.

Angular CLIng new, ng serve, ng g c, ng build — the commands you will use every single day.

Built a real project — Complete multi-component portfolio page with proper Angular structure.


What's Next — Phase 3

In Phase 3 we go much deeper into components. You will learn:

All 8 lifecycle hooks — what they are, when each one runs, and when to use which one. You will understand ngOnInit deeply — the most used lifecycle hook for loading data.

@Input() — how to pass data from a parent component down to a child component. This is how components talk to each other.

@Output() and EventEmitter — how a child component sends events back up to its parent.

@ViewChild — how to access a child component directly from a parent's TypeScript code.

Content projection with ng-content — how to build wrapper components that can display content passed from outside.

How Angular handles component styles and keeps them scoped to their own component.

How Angular's change detection works — how Angular knows when something changed and when to update the screen.

Mean — Complete Chapter for ML & Statistics

What is Mean?

We calculate the mean (average) because it gives a single value that represents the whole dataset.

Why we need mean (benefits):

  • Easy understanding: Instead of looking at many numbers, one value summarizes everything.
  • Quick comparison: You can easily compare different groups (e.g., average salary of two companies).
  • Decision making: Helps in making decisions based on overall performance (e.g., average marks, sales).
  • Finding trends: Shows general behavior of data (high, low, normal).
  • Used in formulas: Mean is the base for many calculations like variance, standard deviation, etc.

Mean is the average of a set of numbers. You add all values together, then divide by how many values there are.

Simple idea: If 5 friends scored 60, 70, 80, 90, 100 in a test — what was the "typical" score? You find the mean.

Formula:

Mean (ฮผ or x̄) = Sum of all values / Total count
              = (x₁ + x₂ + x₃ + ... + xโ‚™) / n

Example:

Values: 60, 70, 80, 90, 100
Sum = 60 + 70 + 80 + 90 + 100 = 400
Count = 5
Mean = 400 / 5 = 80

Why Do We Use Mean?

Because we need one number that represents the whole dataset.

In ML, you can't feed 10,000 raw values into every formula. You need summaries. Mean is the most fundamental summary of data.

It answers: "If everything was equal, what would each value be?"


Types of Mean (All Used in ML)


1. Arithmetic Mean

This is the standard mean everyone knows. Add everything, divide by count.


    import numpy as np

    scores = [60, 70, 80, 90, 100]
    mean = np.mean(scores)
    print(mean)  # 80.0

Used in: Loss functions, accuracy calculation, gradient descent, feature scaling.


2. Weighted Mean

Weighted mean is used when all values are not equally important.

๐Ÿ‘‰ In normal mean, every value has same importance
๐Ÿ‘‰ In weighted mean, some values have more importance (weight) than others

Some values matter MORE than others. You assign a weight to each value.

Formula:

Weighted Mean = (w₁x₁ + w₂x₂ + ... + wโ‚™xโ‚™) / (w₁ + w₂ + ... + wโ‚™)

Example 1: You have 3 exams. Final exam is worth more.


    import numpy as np
    scores  = [70,  80,  90]
    weights = [1,   1,   3]   # Final exam has weight 3

    weighted_mean = np.average(scores, weights=weights)
    print(weighted_mean)  # 84.0

    # Manual: (70*1 + 80*1 + 90*3) / (1+1+3) = 420/5 = 84


Example 2:

Marks:

  • Math = 90 (weight = 50%)
  • English = 80 (weight = 30%)
  • Science = 70 (weight = 20%)

Now we don’t treat all subjects equally.

Weighted Mean =

(90 × 0.5) + (80 × 0.3) + (70 × 0.2)
= 45 + 24 + 14
= 83

Used in: Ensemble models (XGBoost, Random Forest voting), class imbalance handling, recommendation systems.


3. Geometric Mean

๐Ÿค” First Understand the Problem — Why Arithmetic Mean Fails?

Suppose you have ₹100. You invest it:

Year

Return

Your Money

Year 1

+100%

₹100 → ₹200

Year 2

-50%

₹200 → ₹100

Arithmetic Mean says:

Reality check: Your money went ₹100 → ₹200 → ₹100 back. Real return = 0% ๐Ÿ˜

So arithmetic mean showed 25% profit when actually there was 0% profit. This exact problem is solved by Geometric Mean.

๐Ÿง  Core Idea — Growth That Multiplies

Whenever one value grows on top of the previous value (compounding), use Geometric Mean.

Type

Operation

Use When

Arithmetic Mean

Adds numbers

Values are independent

Geometric Mean

Multiplies numbers

Each value depends on previous one

๐Ÿ“ Formula

Two steps only:

  1. Multiply all numbers together
  2. Take the nth root (n = how many numbers you have)

๐Ÿ’ฐ Example 1 — Investment Returns

You have ₹1000. Returns over 3 years:

  • Year 1: +10%
  • Year 2: -20%
  • Year 3: +30%

๐Ÿ”„ Step 0 — Convert % to Multiplier (Most Important Step)

Why do we convert? Because we need to multiply, not add. A multiplier tells us what to multiply the current amount by.

Year

Return

How to Convert

Multiplier

Year 1

+10%

1.00 + 0.10

1.10

Year 2

-20%

1.00 − 0.20

0.80

Year 3

+30%

1.00 + 0.30

1.30

Rule: Always write it as 1 + (percent/100) +10% → 1 + (10/100) = 1 + 0.10 = 1.10 -20% → 1 + (-20/100) = 1 − 0.20 = 0.80

๐Ÿ“Š Step 1 — Multiply All Multipliers

Calculate left to right:

1.10×0.80=0.881.10 \times 0.80 = 0.88
0.88×1.30=1.1440.88 \times 1.30 = 1.144
Product=1.144

๐ŸŒฑ Step 2 — Take the nth Root

Here n = 3 (three years), so we take the cube root:

GM = (1.144)1/3

What does 1/3 power mean?

(1.144)1/3

means "what number multiplied by itself 3 times gives 1.144?"​

๐ŸŽฏ Step 3 — Convert Back to Percentage


✅ Step 4 — Verify the Answer (Proof)

Actual path of money:

Using GM (4.56% every year):

Both give the same final amount — so GM is correct!

What Arithmetic Mean would have given (wrong):

๐Ÿ‘จ‍๐Ÿ‘ฉ‍๐Ÿ‘ง Example 2 — Population Growth

City population = 10,00,000. Growth over 3 years:

  • Year 1: +5%
  • Year 2: +8%
  • Year 3: +6%

๐Ÿ”„ Step 0 — Convert to Multipliers

Year

Growth

Conversion

Multiplier

Year 1

+5%

1 + 0.05

1.05

Year 2

+8%

1 + 0.08

1.08

Year 3

+6%

1 + 0.06

1.06

๐Ÿ“Š Step 1 — Multiply All Multipliers

1.134 × 1.06= 1.20204

Product=1.20204

๐ŸŒฑ Step 2 — Take the Cube Root (n = 3)

๐ŸŽฏ Step 3 — Convert to Percentage

✅ Step 4 — Verify

Actual population growth:

10,00,000×1.05×1.08×1.06=12,02,040

Using GM (6.30% every year):

10,00,000×1.063×1.063×1.063=12,02,040

Both match perfectly!

๐Ÿ” Revisiting the ₹100 Problem (Now With GM)

+100% and -50%:

GM correctly said 0% return. Arithmetic mean had wrongly said +25%.

๐Ÿ Python Code With Explanation


    from scipy.stats import gmean

    # Step 1: Write returns as multipliers
    returns = [1.10, 0.80, 1.30]   # +10%, -20%, +30%

    # Step 2: gmean multiplies all and takes nth root automatically
    gm = gmean(returns)

    # Step 3: Convert back to percentage
    print(f"Geometric Mean : {gm:.4f}")              # 1.0456
    print(f"Avg return/year: {(gm - 1) * 100:.2f}%") # 4.56%

๐Ÿ“Œ When to Use — Quick Reference

Situation

Correct Mean

Average marks, height, weight

Arithmetic Mean

Investment / stock returns

Geometric Mean

Population growth

Geometric Mean

Any % change over time

Geometric Mean

Each value builds on previous

Geometric Mean

๐ŸŽฏ One Line Summary

Whenever money or any quantity grows on top of the previous result (compounding), always use Geometric Mean — Arithmetic Mean will give you a wrong answer.


4. Harmonic Mean

Harmonic Mean is used when values are related to speed, rate, or “per unit” things.

๐Ÿ‘‰ Like:

  • speed (km/h)
  • price per item
  • work per hour

What it actually means

It gives the true average when things are divided (not added or multiplied)

๐Ÿ‘‰ Special case: When you travel the same distance with different speeds

Simple example idea

You go:

  • Half distance at 60 km/h

  • Half distance at 40 km/h

๐Ÿ‘‰ Normal average = (60 + 40) / 2 = 50 ❌ WRONG
๐Ÿ‘‰ Because time taken is different

๐Ÿ‘‰ Harmonic Mean gives correct average speed

Why we need it

  • When values are rates (per unit)

  • When denominator matters (time, distance, etc.)

  • Gives real accurate result in such cases


In one line:

Harmonic mean is used to find the correct average when dealing with speeds or rates (per unit values).

Reciprocal of the arithmetic mean of reciprocals. Sounds complex — but the use case makes it click.

Formula:

Harmonic Mean = n / (1/x₁ + 1/x₂ + ... + 1/xโ‚™)

✅ Example 1 (Average Speed with multiple values)

You travel equal distances at speeds: 30 km/h, 40 km/h, 60 km/h

Step 1: Formula
3(130+140+160)\frac{3}{\left(\frac{1}{30} + \frac{1}{40} + \frac{1}{60}\right)}

Step 2: Solve
1/30 + 1/40 + 1/60
LCM = 120

= (4 + 3 + 2) / 120 = 9/120 = 3/40

Step 3: Final
3 ÷ (3/40) = 40 km/h

๐Ÿ‘‰ Final Answer: Average speed = 40 km/h

✅ Example 2 (Work Rate)

Two machines complete same work:

  • Machine A → 6 hours
  • Machine B → 12 hours

Step 1: Formula

2(16+112)\frac{2}{\left(\frac{1}{6} + \frac{1}{12}\right)}

Step 2: Solve

1/6 + 1/12 = (2 + 1) / 12 = 3/12 = 1/4

Step 3: Final

2 ÷ (1/4) = 8 hours

๐Ÿ‘‰ Final Answer: Average time = 8 hours

Example:


    from scipy.stats import hmean

    values = [4, 1]
    h_mean = hmean(values)
    print(h_mean)  # 1.6

The most important use in ML — F1 Score:

precision = 0.80
recall    = 0.60


    # F1 Score IS the harmonic mean of precision and recall
    f1 = 2 * (precision * recall) / (precision + recall)
    print(f1)  # 0.686

    # Why harmonic and not arithmetic?
    # Arithmetic mean of 0.8 and 0.6 = 0.70 (too generous)
    # Harmonic mean punishes imbalance — if either is low, F1 is low

Used in: F1 Score, averaging rates, anywhere balance between two metrics matters.


5. Moving Average (Rolling Mean)


6. Exponential Moving Average (EMA)


Mean in Core ML Concepts


Mean Absolute Error (MAE)


Mean Squared Error (MSE)


Root Mean Squared Error (RMSE)


Mean in Feature Scaling — Standardization (Z-score)

Before feeding data into ML models, you scale features. Mean is the center point.

Formula:

z = (x - mean) / standard_deviation
from sklearn.preprocessing import StandardScaler

data = [[25], [30], [35], [40], [45]]
scaler = StandardScaler()
scaled = scaler.fit_transform(data)

print(scaled)
# After scaling: mean becomes 0, std becomes 1
# [-1.41, -0.71, 0.0, 0.71, 1.41]

Why? Algorithms like Linear Regression, SVM, KNN, Neural Networks assume features are on similar scales. Without this, the feature with larger numbers dominates unfairly.


Mean in Gradient Descent

When you train a model, the loss function uses mean over all training examples.

Loss = (1/n) × ฮฃ (predicted - actual)²

The gradient (direction to update weights) is also the mean of gradients across all samples. The model learns by minimizing this average error.


Mean Imputation (Handling Missing Data)

When data has missing values, a simple strategy is to fill them with the mean of that column.

import pandas as pd
import numpy as np

df = pd.DataFrame({'age': [25, 30, np.nan, 40, np.nan, 35]})

mean_age = df['age'].mean()  # 32.5
df['age'].fillna(mean_age, inplace=True)

print(df)
# NaN values replaced with 32.5

When to use: Works well when data is roughly normally distributed and not too many values are missing.


Mean in Batch Normalization (Neural Networks)

Inside deep neural networks, after each layer, the activations are normalized using mean and standard deviation of the current batch. This keeps training stable and fast.

import torch
import torch.nn as nn

# PyTorch example
bn = nn.BatchNorm1d(num_features=4)
x = torch.tensor([[1.0, 2.0, 3.0, 4.0],
                   [5.0, 6.0, 7.0, 8.0]])

output = bn(x)
# Internally: subtracts mean, divides by std, for each feature

Mean vs Median — When Mean Fails

Mean has one big weakness: outliers destroy it.

salaries = [30000, 32000, 31000, 29000, 500000]  # one billionaire in the group

mean_salary   = np.mean(salaries)    # 124,400  ← completely misleading
median_salary = np.median(salaries)  # 31,000   ← represents the group better

Rule of thumb:

  • Data has no extreme outliers → use Mean
  • Data has outliers or is skewed → use Median
  • Always check with a histogram or box plot before deciding

Quick Reference Summary

Type               Formula                   ML Use Case
─────────────────────────────────────────────────────────────────────
Arithmetic Mean    sum / n                   Loss functions, scaling
Weighted Mean      ฮฃ(wแตขxแตข) / ฮฃwแตข            Ensembles, class weights
Geometric Mean     (x₁×x₂×...×xโ‚™)^(1/n)    Growth rates, log-scale eval
Harmonic Mean      n / ฮฃ(1/xแตข)              F1 Score, rate averaging
Rolling Mean       Mean of last k values     Time series smoothing
EMA                Weighted recent average   Adam optimizer, forecasting
MAE                mean(|actual - pred|)     Regression evaluation
MSE                mean((actual - pred)²)    Regression loss function
RMSE               √MSE                      Regression evaluation

One-Line Memory Hook for Each

  • Arithmetic → "The everyday average"
  • Weighted → "Some things matter more"
  • Geometric → "For growth and multiplication"
  • Harmonic → "For rates and balance — F1 lives here"
  • Rolling → "Sliding window over time"
  • EMA → "Recent past matters more"
  • MAE → "Average of how wrong you were"
  • MSE → "Punish big mistakes harder"
  • RMSE → "MSE in original units"

That's the complete Mean chapter — from the basic definition all the way to how it powers neural network training, model evaluation, and data preprocessing in real ML pipelines.


Phase 2 — Angular Fundamentals

Chapter 1 — What is Angular and How Does it Think? 1.1 — What is Angular? Angular is a framework for building web applications. A framewo...