Skip to content
Tutorials Center
My learning

Topics

Lesson 5 of 74 ยท Getting Started

How Angular Works

See what happens between your code and the screen - the AOT compiler, template instructions, bootstrapping, the component tree, zone-less change detection and the esbuild build.

You can write Angular for months without knowing what happens under the hood, but a rough mental model will save you hours of confusion. Why does a typo in a template stop the build? Why does the page update when you click a button? Why is the production bundle so much smaller than the development one? All three answers come from the same short story: Angular is a compiler plus a small runtime.

This lesson tells that story in two parts: what happens at build time, when the CLI turns your files into JavaScript, and what happens at run time, when the browser starts the application and keeps it up to date. As before, the Angular snippets are real or clearly labeled as simplified, and the two runnable examples are stand-ins that model the ideas.

Build time: from your files to JavaScript

Browsers understand JavaScript, HTML and CSS. They do not understand TypeScript, or Angular templates, or @if blocks. So the build does these steps:

  1. TypeScript is checked and converted to JavaScript.
  2. The Angular compiler reads every @Component decorator and its template, checks the template against the class (is name a real property? does that child component exist?) and converts the template into JavaScript code.
  3. A bundler joins all modules into a few files, removes code nobody uses (tree-shaking), minifies, splits lazy-loaded routes into separate chunks and writes hashed file names for caching.
flowchart LR
  S["Your code<br/>.ts, .html, .css"] --> T["TypeScript check"]
  T --> N["Angular compiler<br/>templates to JavaScript"]
  N --> B["Bundler: esbuild<br/>tree-shake, minify, split"]
  B --> D["dist folder<br/>static files"]

The CLI runs your sources through the Angular compiler and the bundler; the browser only ever receives plain JavaScript.

AOT and Ivy

Compiling templates ahead of time (AOT) means the work happens on your machine or in CI, not in the user's browser. It is the default for both ng serve and ng build. The benefits are speed (the browser skips compiling), safety (template errors become build errors, and templates are analyzed so dangerous patterns can be rejected) and size (unused features can be removed).

The current compiler and runtime are called Ivy. Its design goal is that each component compiles to a self-contained set of instructions, so bundlers can drop whatever a component does not use.

Templates become instructions

An Angular template does not turn into a string of HTML. It becomes a function that calls small runtime instructions to create DOM elements once and to update only the dynamic parts later. The next block is a simplified illustration of the shape of that output for <h2>Hello, {{ name }}!</h2>. The exact names and arguments change between versions, so do not rely on them:

JavaScript
// Illustrative and simplified; real output differs between versions.
function Greeting_Template(rf, ctx) {
  if (rf & 1) {
    // creation mode: runs once
    ษตษตelementStart(0, 'h2');
    ษตษตtext(1);
    ษตษตelementEnd();
  }
  if (rf & 2) {
    // update mode: runs on every check
    ษตษตadvance(1);
    ษตษตtextInterpolate1('Hello, ', ctx.name, '!');
  }
}

There are two phases. Creation mode builds the DOM nodes. Update mode only re-evaluates bindings such as name and writes to the page when a value really differs. There is no virtual DOM tree being diffed: the compiler already knows which text nodes and properties are dynamic, so it updates those directly.

Stand-in 1: a miniature template compiler

The first stand-in compiles a template string into an instruction list, runs creation once, then runs update passes and counts how many DOM writes each pass makes. It is a toy (it supports only elements, text and {{ }}), but the creation/update split is the real design.

TypeScript A stand-in: compile a template into instructions, then update

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The second pass writes nothing because no value changed, and the third writes exactly one text node. Real Angular's update instructions follow the same rule: compare, then write only if different.

JIT versus AOT, and what ng build produces

Angular can compile a template at two different moments.

  • AOT (ahead of time) compiles templates during the build. The browser receives finished JavaScript instructions and no compiler. This is the default for ng serve and ng build.
  • JIT (just in time) ships the Angular compiler to the browser and compiles each template when the component is first used. It was the default for development before Angular 9. Today it is mainly used by some test setups, where a component is compiled on the fly, and by dynamic scenarios that build components from strings. It is not what a normal app serves.

The practical differences:

AOT JIT
Where templates compile On your machine or CI In the user's browser
Template typos Build errors Runtime errors, when the component first renders
Bundle No compiler included Includes the compiler (a large extra download)
First render Fast Slower, compile first
Tree-shaking Works well Limited, the compiler must keep everything it might need

The stand-in below shows the idea with a toy template. The "AOT" path checks every binding name when it is built, so a typo fails before anyone opens the page. The "JIT" path only discovers the same typo when it renders.

TypeScript AOT finds the typo at build time, JIT at render time

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Real Angular's AOT check is stronger than this toy: with strictTemplates on, it type-checks every binding, input and output against your TypeScript classes.

What ng build writes

A production build creates a dist/<project>/ folder. For a client-side app the files in browser/ are all you deploy:

TEXT
dist/my-app/browser/
  index.html              (the page, with preload and script tags added)
  main-4F2A9C1B.js        (your code and the framework pieces you use)
  chunk-8E31D0AA.js       (shared code and each lazy-loaded route)
  polyfills-B6K2Q9ZP.js   (only if you listed polyfills)
  styles-3C7D5E11.css     (global styles)
  favicon.ico
  3rdpartylicenses.txt    (licenses of bundled packages)
  prerendered-routes.json (only with prerendering)

Two details matter. First, file names contain a content hash: when the file changes, its name changes, so hosts can cache old names forever and users still get fresh code. Second, every lazy route (loadComponent, loadChildren, @defer) becomes its own chunk, so the first page downloads only what it needs. The build also prints a table with raw and compressed sizes per file and fails if a configured budget is exceeded. Hosting and caching rules are in Build and Deploy; the --stats-json flag writes a file that bundle analyzers can read when you want to know why a chunk is large.

Run time: bootstrapping

When the browser loads your bundle, main.ts calls bootstrapApplication(App, appConfig). Roughly, Angular then:

  1. Creates the platform and an application-wide injector from your providers (the dependency injection system from the later chapter).
  2. Finds the element that matches the root component's selector (<app-root> in index.html).
  3. Creates the root component, runs its template's creation mode, which creates child components in turn, and renders the first view.
  4. Starts watching for reasons to run change detection again.

The result is the component tree from the previous lesson: every component instance is attached to a host element, and every parent owns its children. Change detection walks that tree from the top.

Run time: knowing when to update

Something has to tell Angular "data may have changed, run update mode". Historically that was Zone.js, a library that patches browser APIs (events, timers, promises, HTTP callbacks). After any patched callback finished, Zone.js told Angular, and Angular checked the whole tree. It works without any effort from you, at the cost of extra checks and a larger bundle.

The direction of the framework is zone-less change detection driven by signals and explicit notifications: a signal read in a template tells Angular exactly which view to refresh when it changes, and event listeners that the template registers also schedule a refresh. You opt in with a provider such as provideZonelessChangeDetection() in app.config.ts. Its status depends on your Angular version (it started as experimental and has been maturing), so check the release notes before relying on it. Whether the global trigger is Zone.js or signals, the update half works as in the stand-in above. The change detection lesson goes deeper.

The development server and the production build

Both ng serve and ng build use the application builder, based on esbuild (a very fast bundler written in Go), and the dev server is built on Vite. That is why a rebuild after saving a file takes a fraction of a second. Production builds additionally minify, enable optimizations and fail if a configured size budget is exceeded. If you used an Angular project from several years ago, you may remember webpack; it is no longer the default.

Stand-in 2: render a component tree to a string

The last stand-in builds a small tree of component definitions, renders it to nested host elements and then walks it in the order change detection would, top to bottom. It helps to see the tree.

TypeScript A stand-in: render a component tree and walk it

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Notice that app-product-card appears twice, and each use is a separate instance in the tree. A change-detection pass visits parents before children, and a smart strategy can skip whole subtrees, which is exactly what OnPush and signals exploit in later lessons.

Do not memorize compiler details. What matters for daily work: templates are compiled and type-checked at build time, a view has a creation phase and cheap update phases, and Angular needs a trigger (Zone.js or signals) to know when to run an update.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does ahead-of-time (AOT) compilation mean in Angular?

    AOT compiles templates during the build. The browser skips compiling, template errors become build errors, and unused code can be removed.
  2. 2. In a compiled template, what is the difference between creation mode and update mode?

    The template function has two phases. Creation builds the nodes once. Update checks the dynamic bindings on later passes and touches the DOM only for values that changed.
  3. 3. What is the role of Zone.js in classic Angular applications?

    Zone.js wraps events, timers and promises. When a patched callback finishes, Angular is told to check the tree. Zone-less mode replaces this trigger with signals and explicit notifications.
  4. 4. Which tools does the default Angular application builder use?

    New projects use the application builder, based on esbuild, with Vite powering ng serve. Older projects used webpack.

Summary

  • Angular is a compiler plus a small runtime: the build turns TypeScript and templates into plain JavaScript bundles.
  • AOT compilation checks templates against classes at build time, which catches errors early and keeps bundles small.
  • A compiled template is a function with a creation phase (build DOM once) and an update phase (re-check bindings, write only differences).
  • bootstrapApplication creates the injector, finds the root element, renders the root component and its children, then starts change detection.
  • Zone.js has historically told Angular when to check; zone-less change detection driven by signals is the direction of the framework.
  • The default builder uses esbuild, with Vite for ng serve.

Next: Interpolation and Template Expressions