Web & Mobile Development

Angular Fundamentals: Standalone Components, Signals and the Modern APIs

Intermediate8 min readUpdated

Angular changed substantially between the NgModule era and the current releases: components are standalone by default, signals carry state, templates use built-in control-flow blocks, and change detection can run without Zone.js. This guide teaches the framework as it is now, from a first component through dependency injection, HTTP, routing, reactive forms and the change-detection model that ties them together.

What you will learn

  • Create standalone components and understand how an application bootstraps without NgModules
  • Bind data in templates using the built-in control-flow blocks and signal inputs
  • Model state with signals, computed values and effects, and know when RxJS is still the better tool
  • Inject services, configure HttpClient and the router with provider functions
  • Build and validate reactive forms, and explain how change detection decides what to re-render

If you last used Angular in the era of NgModule, @Input() decorators and *ngFor, the framework you find today will look different in almost every file. Components are standalone, state is held in signals, templates use block syntax for conditionals and loops, providers come from functions rather than module metadata, and change detection can run without Zone.js at all. The architecture — components, templates, dependency injection, a router — is recognisably the same; the ergonomics are not.

This guide teaches the current shape of the framework rather than the historical one. It starts with a single component, adds state, services, HTTP and routing, then explains the change-detection model that makes the rest predictable. Everything here assumes TypeScript, which Angular does not merely tolerate but depends on: decorator metadata, injection tokens and typed forms all rely on it.

The unit of an application: a component

A component is a TypeScript class with a decorator that binds it to a template and some styles. Nothing else is required — no module declares it, no barrel file registers it.

import { Component, signal, computed, input, output } from '@angular/core';

@Component({
  selector: 'app-order-row',
  template: `
    <tr [class.selected]="selected()">
      <td>{{ order().reference }}</td>
      <td>{{ order().total | currency: 'EUR' }}</td>
      <td><button type="button" (click)="remove.emit(order().id)">Remove</button></td>
    </tr>
  `,
  styles: `.selected { background: var(--highlight); }`,
})
export class OrderRowComponent {
  readonly order = input.required<Order>();
  readonly selected = input(false);
  readonly remove = output<string>();
}

Several things are worth naming. input() and output() are functions rather than decorators, and input.required<T>() makes the compiler enforce that a caller supplies the value. An input created this way is a signal: you read it by calling it, and anything derived from it updates automatically. The selector is what the tag looks like where the component is used; the imports array — omitted here because the template uses no other components — is where a standalone component lists the components, directives and pipes its template needs.

TypeScript carries real weight here. Interfaces describe the shapes crossing component boundaries, generics type the inputs and the HTTP responses, and enabling strict in tsconfig.json is the difference between the compiler catching a null and the browser reporting it.

An application starts by bootstrapping a root component with a list of providers:

import { bootstrapApplication } from '@angular/platform-browser';
import { provideRouter, withComponentInputBinding } from '@angular/router';
import { provideHttpClient, withFetch, withInterceptors } from '@angular/common/http';

bootstrapApplication(AppComponent, {
  providers: [
    provideRouter(routes, withComponentInputBinding()),
    provideHttpClient(withFetch(), withInterceptors([authInterceptor])),
  ],
});

Templates: bindings and block control flow

Angular templates are HTML with four binding forms. Interpolation with double braces renders a value as text. Square brackets bind a property — [disabled]="isBusy()" sets the DOM property, not the attribute. Parentheses bind an event — (click)="save()". And the banana-in-a-box [(ngModel)] combines both directions, which is only sugar for a property binding plus an event binding.

Structural logic now uses built-in blocks instead of the old asterisk directives:

@Component({
  selector: 'app-orders',
  template: `
    @if (orders().length > 0) {
      <table>
        @for (order of orders(); track order.id) {
          <app-order-row [order]="order" (remove)="delete($event)" />
        } @empty {
          <tr><td>Nothing to show</td></tr>
        }
      </table>
    } @else {
      <p>Loading…</p>
    }

    @switch (status()) {
      @case ('draft')     { <app-draft-banner /> }
      @case ('submitted') { <app-submitted-banner /> }
      @default            { <app-unknown-banner /> }
    }

    @defer (on viewport) {
      <app-revenue-chart [data]="chartData()" />
    } @placeholder {
      <div class="skeleton"></div>
    }
  `,
  imports: [OrderRowComponent, DraftBannerComponent],
})
export class OrdersComponent { /* … */ }

The blocks are part of the template language rather than directives, so nothing needs importing, the compiler can type-check inside them, and they produce smaller, faster output. The track expression on @for is mandatory, and it matters: it tells Angular how to match items between renders so it can move DOM nodes instead of destroying and rebuilding them. Tracking by index on a reordering list is a classic source of lost input state. @defer is a genuinely new capability — it code-splits everything inside it and loads it on a trigger such as entering the viewport, hovering, or an idle callback.

Pipes transform a value in the template. currency, date, json, async and keyvalue cover most needs, and a custom pure pipe is a cheap way to format without adding a method call to every change-detection pass.

Signals: state the framework can track

A signal is a value container that records who reads it. When it changes, exactly those readers are notified — nothing else is re-evaluated.

import { Component, signal, computed, effect } from '@angular/core';

@Component({ /* … */ })
export class CartComponent {
  readonly items = signal<CartItem[]>([]);
  readonly coupon = signal<string | null>(null);

  readonly subtotal = computed(() =>
    this.items().reduce((sum, item) => sum + item.price * item.quantity, 0),
  );
  readonly total = computed(() =>
    this.coupon() ? this.subtotal() * 0.9 : this.subtotal(),
  );

  constructor() {
    effect(() => localStorage.setItem('cart', JSON.stringify(this.items())));
  }

  add(item: CartItem) {
    this.items.update((current) => [...current, item]);   // new array, not push
  }
}

Read a signal by calling it. Write with set for a replacement or update for a function of the previous value. computed derives a value lazily and caches it until one of its dependencies changes, so total above recalculates only when items or coupon does. effect runs side effects when its dependencies change and is for synchronising with things outside Angular — storage, a charting library, logging — not for writing back into other signals.

The rule that makes all of this work is immutability. this.items.update(list => [...list, item]) produces a new array and notifies readers; this.items().push(item) mutates in place and notifies nobody. That is the same discipline described in JavaScript fundamentals, and here the framework depends on it.

Signals also power the query and model APIs: viewChild() and contentChild() return signals of the matched element, and model() creates a two-way bindable signal input.

Dependency injection and services

Angular's injector is hierarchical: it starts at the component and walks up through parent components to the application root. A service is an ordinary class marked injectable, and providedIn: 'root' makes it a singleton that is tree-shaken away if nothing injects it.

import { Injectable, inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({ providedIn: 'root' })
export class OrderService {
  private readonly http = inject(HttpClient);

  list(page: number) {
    return this.http.get<Page<Order>>('/api/orders', { params: { page } });
  }

  create(draft: OrderDraft) {
    return this.http.post<Order>('/api/orders', draft);
  }
}

The inject() function has largely replaced constructor parameter injection. It works in field initialisers, in factory functions and inside provide* helpers, and it composes: you can write a small reusable function that itself calls inject(). Constructor injection still works and is still what you will see in older files.

Injection tokens let you inject things that are not classes — a configuration object, a base URL, a feature flag — and providing a different implementation for the same token is how you swap a real service for a fake in tests or a mock backend in development.

HTTP, and where the errors go

HttpClient returns cold observables: nothing is sent until something subscribes, and unsubscribing cancels the request. Configure it once with provideHttpClient(withFetch()), which uses the platform fetch implementation underneath.

this.orders.list(1).subscribe({
  next: (page) => this.items.set(page.content),
  error: (error: HttpErrorResponse) => this.message.set(describe(error.status)),
});

Interceptors are plain functions in the current API and are the right place for authentication headers, correlation ids, retry policy and centralised error mapping:

export const authInterceptor: HttpInterceptorFn = (req, next) => {
  const token = inject(TokenStore).current();
  return next(token ? req.clone({ setHeaders: { Authorization: `Bearer ${token}` } }) : req);
};

Unlike fetch, HttpClient treats a non-2xx response as an error, so status handling lives in the error callback. Deciding what each code means to the user — retry, re-authenticate, show a validation message — is worth doing deliberately; the HTTP status code reference covers the distinctions, and REST API design covers the server side of the same contract.

Newer releases add a resource API that wraps an asynchronous load in signals, exposing value, loading and error as signals and re-fetching when its request signal changes. It removes a lot of the boilerplate around "load this when that changes" and is worth checking in the current documentation before hand-rolling it.

Routing

Routes are a plain array, and lazy loading is a dynamic import:

export const routes: Routes = [
  { path: '', component: HomeComponent, title: 'Home' },
  {
    path: 'orders',
    loadChildren: () => import('./orders/routes').then((m) => m.ORDER_ROUTES),
    canActivate: [authGuard],
  },
  { path: 'orders/:id', loadComponent: () => import('./orders/detail').then((m) => m.OrderDetailComponent) },
  { path: '**', component: NotFoundComponent },
];

loadComponent and loadChildren split the bundle at the route boundary, which is the highest-leverage performance decision in a large application. Guards are functions that return a boolean, a UrlTree or an observable of either. With withComponentInputBinding() enabled, route parameters, query parameters and resolved data are bound straight to component inputs, so a component reading id = input.required<string>() needs no router injection at all.

Reactive forms

Reactive forms define the model in TypeScript, which makes it typed and testable without rendering anything.

private readonly fb = inject(NonNullableFormBuilder);

readonly form = this.fb.group({
  reference: this.fb.control('', [Validators.required, Validators.maxLength(20)]),
  email: this.fb.control('', [Validators.required, Validators.email]),
  quantity: this.fb.control(1, [Validators.min(1), Validators.max(50)]),
});

submit() {
  if (this.form.invalid) {
    this.form.markAllAsTouched();
    return;
  }
  this.orders.create(this.form.getRawValue()).subscribe(/* … */);
}

Each control exposes value, valid, errors, dirty, touched and a valueChanges observable. Custom validators are functions returning an error map or null, and asynchronous validators return an observable — the usual way to check a value against the server while typing, debounced. Only show an error once the control is touched or the form has been submitted; validating as the user types their first character is the most common usability mistake in Angular forms.

How change detection decides what to re-render

Historically, Angular relied on Zone.js, which monkey-patches timers, event listeners and XHR so that the framework learns when anything asynchronous completes. On each such event it walks the component tree from the root and re-evaluates every template binding. That is why the framework felt "automatic" and also why large screens got slow.

ChangeDetectionStrategy.OnPush narrows this: a component is checked only when an input changes by reference, an event originates inside it, a signal it reads changes, or something marks it dirty. Combined with immutable updates it turns a whole-tree walk into a path from the root to the components that actually changed.

Signals push this further, because reading one in a template registers a precise dependency. That makes the tree walk unnecessary, which is what enables zoneless change detection: with provideZonelessChangeDetection() the application drops the Zone.js dependency entirely and schedules a check when a signal changes or an event fires. Smaller bundle, cleaner stack traces, and no more mysterious extra cycles. It requires that all state the template reads is either a signal or something that explicitly marks the component dirty, which is why signal-first code is the recommended default for new applications.

RxJS, project layout and testing

RxJS has not gone away; its scope has narrowed to what it is genuinely good at — streams over time. Debouncing a search box with debounceTime, cancelling a superseded request with switchMap, retrying with backoff, combining several sources: none of that has a signal equivalent. The idiomatic bridge is toSignal(), which turns an observable into a signal the template can read without the async pipe and without manual unsubscription. For component state that is simply "the current value of something", signals are less machinery and less to get wrong.

The CLI generates and maintains the project. ng new, ng generate component orders/order-row, ng serve, ng build, ng test and ng update cover daily work, and ng update runs schematics that rewrite your code for breaking changes — which is why staying close to the current version is far cheaper than skipping several. Organise by feature rather than by type: an orders folder containing its components, service, routes and models beats parallel components and services trees that force every change to touch four directories.

For testing, TestBed configures a miniature injector so a component can be rendered with fake providers, while a service with injected dependencies can usually be tested as a plain class with no framework involvement at all. Test signal-driven logic by setting inputs and reading computed values; keep end-to-end coverage for the flows that cross components.

Key takeaways

  • Standalone components are the default: no NgModules, bootstrapApplication at the root, and providers supplied by provide* functions.
  • Templates use block control flow — @if, @for with a mandatory track, @switch and @defer — which the compiler understands directly.
  • Signals hold state, computed derives it lazily, and effect synchronises with the outside world; updates must be immutable for any of it to work.
  • inject() is the modern way to reach services, interceptors are plain functions, and HttpClient observables are cold and cancellable.
  • OnPush and signals shrink change detection from a full tree walk to a targeted update, which is what makes zoneless applications possible.
  • Keep RxJS for time-based streams and bridge with toSignal(); organise by feature and let ng update carry you across versions.

Sources and further reading

Frequently asked questions

Do I still need NgModules?
Not for new code. Components, directives and pipes are standalone by default, applications bootstrap with bootstrapApplication and providers are supplied by functions such as provideRouter and provideHttpClient. NgModules remain supported so that large existing applications keep working and can migrate gradually, and some third-party libraries still ship them, but nothing in a new project needs to declare one.
Are signals a replacement for RxJS?
They overlap but solve different problems. Signals model synchronous state that the template reads, with automatic dependency tracking and no subscription management. RxJS models streams of events over time and gives you operators for debouncing, retrying, cancelling and combining asynchronous work. Typical modern code uses signals for component state and RxJS for HTTP and event pipelines, bridging with toSignal.
What does OnPush change detection actually do?
By default Angular checks every component in the tree after anything asynchronous happens. With OnPush, a component is only checked when one of its inputs changes by reference, an event fires inside it, a signal it reads changes, or it is marked dirty explicitly. On a large screen this removes most of the work per cycle. Signal-based components make the behaviour predictable, which is what allows zoneless applications.
Reactive forms or template-driven forms?
Prefer reactive forms for anything beyond a two-field search box. The form model is defined in TypeScript, so it is typed, unit-testable without rendering, and easy to compose, and dynamic controls or cross-field validators are straightforward. Template-driven forms put the model in the markup with ngModel, which is quicker for trivial cases but becomes hard to test and to reason about as validation grows.