Introduction to Angular

Introduction to Angular in Angular: Picture a construction company that does not hand you a pile of lumber, wire, and pipe and wish you luck.

The Analogy: A Factory-Built Modular Building

Picture a construction company that does not hand you a pile of lumber, wire, and pipe and wish you luck. Instead it runs a factory that builds finished rooms -- a bathroom pod, a kitchen module, a bedroom unit -- each one wired, plumbed, inspected, and stamped to a single published standard before it ever leaves the plant. On site, a crane lifts each module onto a steel chassis, and every module's connectors line up with the chassis's electrical bus and plumbing manifold because they were all built to the same spec. The contractor supplies the crane, the crew, and the inspection paperwork; you do not source your own elevator or argue with three vendors about whether their parts fit together.

Angular is that turnkey contractor. It is not a single library you bolt onto a page; it is a platform that ships the framing and the fittings together -- a component system, a template compiler, a router, an HTTP client, a forms engine, and a test setup -- all built to one convention so they interlock. The Angular CLI is the factory and the crane crew: ng new pours the chassis (the workspace and build pipeline), and ng generate stamps out a new unit to spec so it drops into place without custom adapters. Because the pieces share a standard, a developer joining the project already knows where the plumbing runs.

A single factory-built room is a component: a self-contained unit with its own walls (the template), its own wiring and logic (the TypeScript class), and a stamped label on the door (the selector) so the crane knows where it goes. Rooms nest -- a suite module contains a bathroom pod -- exactly as an Angular component's template hosts child components. The steel chassis that the rooms bolt onto, distributing power and water to every unit, is the application shell that Angular bootstraps at startup; it is the one fixed point from which the whole structure grows.

The failure mode is the module that ignores the standard. Suppose a subcontractor fabricates a beautiful room off-site but routes its electrical junction two inches from where the chassis bus expects it, or omits the stamped label entirely. The crane arrives, the module will not seat, the connectors do not mate, and the whole lift stalls while someone re-cuts a bracket in the field. In Angular this is the component you forgot to declare or import, the selector that does not match the tag you wrote, or the hand-rolled widget that pokes at the DOM directly and fights the framework's change detection. The strength of a standardized system is also its rigidity: parts that honor the convention snap together effortlessly, and parts that do not simply refuse to fit.


Syntax or Core Structure

Every Angular application is a tree of components, and every component is the same three things bound together by a decorator: a class that holds data and logic, a template that describes the markup, and metadata that tells Angular how to wire them up. The @Component decorator carries that metadata.

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

@Component({
  selector: 'app-greeting',
  standalone: true,
  template: `
    <h1>Hello, {{ name }}!</h1>
    <p>You have {{ count }} new messages.</p>
  `
})
export class GreetingComponent {
  name = 'Ada';
  count = 3;
}

Angular reads name and count off the component instance, replaces each {{ ... }} interpolation with the current value, and renders:

Output:

Hello, Ada!
You have 3 new messages.

The double braces are interpolation -- a one-way binding from the class to the DOM. When count changes, Angular's change detection re-evaluates the expression and updates only that text node. You never call document.querySelector or set innerHTML; you change a field and describe the result declaratively, and the framework reconciles the view.


Technical Depth: The Four Building Blocks

An Angular app is assembled from a small, fixed vocabulary of parts. Learn these four and the rest of the framework is variations on them.

Components, Templates, and Metadata

A component is a class decorated with @Component. The selector is the custom tag you place in other templates to render it; template (or templateUrl) is the markup; the class body holds the state and methods the template binds to. The decorator is not cosmetic: it is metadata the Angular compiler reads to generate the code that creates the element, wires up its bindings, and connects it to change detection. Strip the decorator and the class is just a class; add it and the same class becomes a renderable building block the crane can seat. You use the component above by writing its tag inside another component's template:

<app-greeting></app-greeting>

The Vocabulary at a Glance

Building blockRole in the appModular-building analogy
ComponentA unit of UI plus its logicA factory-built room
TemplateThe markup a component rendersThe room's interior walls
ServiceShared logic and state, injected on demandThe central utility supply
ImportsDeclares what a template may useThe parts catalog for a lift

Change Detection and Pure Logic

Angular keeps the DOM in sync with your data by running change detection: after any event -- a click, an HTTP response, a timer -- it walks the component tree, re-evaluates each binding expression, and updates the DOM wherever a value changed. Expressions you bind should therefore be cheap and predictable. A pure function of its inputs is ideal, because the same input always yields the same output:

function statusLabel(level) {
  if (level >= 90) return 'Critical';
  if (level >= 70) return 'Warning';
  if (level >= 40) return 'Nominal';
  return 'Idle';
}

[95, 72, 55, 20].forEach(level => console.log(level + ' -> ' + statusLabel(level)));

Output:

95 -> Critical
72 -> Warning
55 -> Nominal
20 -> Idle

In a template you would write {{ statusLabel(sensor.level) }}. The mapping is fully deterministic, which makes the rendered view easy to reason about -- though, as the Real World example shows, calling a method from a template carries a hidden cost.

Modules Versus Standalone Components

Older Angular grouped components into an @NgModule that listed them in declarations and pulled in dependencies through imports. Modern Angular (v15 and later) prefers standalone components that set standalone: true and carry their own imports array, removing the module middleman for most apps. The two styles interoperate -- a standalone component can be imported into an old @NgModule, and a module's exports can be consumed by a standalone component -- so teams migrate incrementally instead of rewriting. What never changes is the contract: something must declare that a component exists before a template may use its tag, exactly as a lift manifest must list a module before the crane will hoist it. Either way, the batteries stay included:

ConcernAngular ships itLibrary-first stack
RoutingBuilt-in RouterAdd a third-party router
HTTPBuilt-in HttpClientAdd a fetch wrapper
FormsReactive and template formsAdd a forms library
Build and testCLI plus bundler and runnerAssemble your own toolchain

Real World Example: A Server Health Panel

A monitoring dashboard needs to list servers and flag the ones in trouble. Here is a standalone component that renders one row per server and reports how many are critical.

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

interface Server {
  name: string;
  level: number;
}

@Component({
  selector: 'app-health-panel',
  standalone: true,
  template: `
    <h2>Server Health</h2>
    <ul>
      <li *ngFor="let s of servers">
        {{ s.name }} | {{ s.level }} | {{ statusLabel(s.level) }}
      </li>
    </ul>
    <p>Critical: {{ criticalCount }}</p>
  `
})
export class HealthPanelComponent {
  servers: Server[] = [
    { name: 'web-01', level: 95 },
    { name: 'api-02', level: 72 },
    { name: 'db-01', level: 55 },
    { name: 'cache-1', level: 20 },
  ];

  statusLabel(level: number): string {
    if (level >= 90) return 'Critical';
    if (level >= 70) return 'Warning';
    if (level >= 40) return 'Nominal';
    return 'Idle';
  }

  get criticalCount(): number {
    return this.servers.filter(s => s.level >= 90).length;
  }
}

The logic that drives the view is plain, pure JavaScript. Modeling it directly reproduces exactly what the template renders, row for row:

const servers = [
  { name: 'web-01', level: 95 },
  { name: 'api-02', level: 72 },
  { name: 'db-01', level: 55 },
  { name: 'cache-1', level: 20 },
];

function statusLabel(level) {
  if (level >= 90) return 'Critical';
  if (level >= 70) return 'Warning';
  if (level >= 40) return 'Nominal';
  return 'Idle';
}

servers.forEach(s => console.log(s.name + ' | ' + s.level + ' | ' + statusLabel(s.level)));
console.log('Critical: ' + servers.filter(s => s.level >= 90).length);

Output:

web-01 | 95 | Critical
api-02 | 72 | Warning
db-01 | 55 | Nominal
cache-1 | 20 | Idle
Critical: 1

The component holds an array of servers and two pieces of derived information: a per-row status label and a count of critical servers. The *ngFor structural directive repeats the <li> template once per server, and each interpolation pulls a value off the current row. The criticalCount getter filters the array and returns the number the footer displays.

Mapped back to the analogy, this component is one factory-built room: the class is its wiring, the template is its interior finish, and the app-health-panel selector is the stamped label the crane reads to seat it on the chassis. The data lives inside the room, and nothing outside reaches in to rearrange the furniture; other components ask for a health panel by its tag and receive a fully finished unit.

Every time change detection runs, Angular re-evaluates the bindings for each row and redraws whatever changed. With four servers you never notice the work, and the code reads cleanly -- which is exactly what makes the next point easy to miss.

The design flaw is calling statusLabel(s.level) and reading the criticalCount getter straight from the template. Angular cannot tell whether these are cheap or cached, so it re-invokes the method for every row and re-runs the getter on every change detection pass -- and that pass fires on every click, keystroke, timer, and HTTP response anywhere in the app, not only when servers changes. At four rows it is invisible; at four thousand rows, with a getter that filters the whole array each pass, the panel stutters on unrelated events. The fix is to lift derived values out of the template's hot path: precompute each label when the data loads, expose criticalCount as a plain field updated only when servers changes, or use a pure pipe so Angular can memoize by input. Template method calls read innocently and scale terribly.


Common Mistakes

  1. Forgetting to declare or import the component. A component only renders if Angular knows about it: listed in some @NgModule's declarations, or in a standalone component's imports. Miss this and the tag renders empty, often with no obvious error.
  2. Selector and tag mismatch. Writing <app-greetings> when the selector is app-greeting produces nothing. The tag must match the selector character for character.
  3. Heavy work in template expressions. Calling methods or filtering arrays inside {{ }} or a getter runs on every change detection pass, not just when the data changes. Keep template expressions to simple field reads.
  4. Mutating data in place and expecting an update. With OnPush change detection, this.items.push(x) may go unnoticed because the array reference did not change. Replace the reference instead: this.items = [...this.items, x].
  5. Reaching for the DOM directly. Using document.querySelector or innerHTML fights change detection, breaks server-side rendering, and invites injection bugs. Bind to data and let Angular touch the DOM.
  6. Confusing interpolation with property binding. {{ url }} renders text; [src]="url" sets a property. For non-string properties and dynamic attributes, use the bracket form.
  7. Putting input-dependent logic in the constructor. A component's @Input values are not set when the constructor runs; read them in ngOnInit instead.
  8. Mixing standalone and NgModule registration. Declaring a standalone component in declarations, or importing a non-standalone one via imports, throws at compile time. Pick one model per component.
  9. Assuming the component lives forever. Subscriptions and timers started in a component must be torn down when it is destroyed, or they leak; later lessons cover the async pipe and takeUntilDestroyed.

Best Practices

  • Keep templates declarative. Derive display values in the class or a pure pipe, not in template method calls, so change detection stays cheap.
  • Prefer standalone components for new code. Explicit imports and no module boilerplate make dependencies obvious and testing simpler.
  • Give each component one responsibility. Small, focused components compose and reuse; large ones accumulate flags and special cases.
  • Type your data with interfaces. Modeling shapes like Server lets the compiler catch a misspelled field before it reaches the browser.
  • Let the CLI scaffold. ng generate component wires the selector, spec file, and registration to convention every time.
  • Adopt OnPush for data-driven components. Treat inputs as immutable and swap references; the view updates predictably and does less work.
  • Prefix selectors with your app tag. A prefix such as app- avoids clashes with native elements and signals ownership.
  • Read the compiler's template errors. Angular's template type checking is precise and usually names the exact binding at fault.

Practice Exercises

  1. Build a profile card. Create a standalone ProfileCardComponent with name, role, and years fields and a template that renders "Ada -- Engineer (7 yrs)" using interpolation. Confirm the rendered text matches the field values exactly.
  2. Add a derived label. Give the card a seniority value computed from years (0 to 2 is Junior, 3 to 6 is Mid, 7 or more is Senior). Compute it as a plain field set when the data is assigned, not as a template method call, and display it.
  3. Trace change detection. Add a button that increments a clicks counter and a second field that never changes. In a comment, explain which bindings Angular re-evaluates when the button is pressed, and why the unchanging one is still visited.
  4. Fix the health panel. Refactor HealthPanelComponent so statusLabel is applied once when servers is assigned (store each row's label alongside its data) and criticalCount becomes a plain field updated only on assignment. Verify the rendered output is identical to the original.