My account

Angular fundamentals

In modern Angular every component is standalone and says itself what it needs. Data that changes lives in a signal, derived values are built with computed, and shared data lives in a service you get with inject. Load pages and heavy parts lazily so the app opens fast.

Not reviewedWritten with AI helpReading time: 15 minOnline shop exampleAngular 20 code

Author: bezzad

Contents

The problem: one cart, many places on the page

In our online shop, the cart shows up in several places:

  1. In the header, a small badge shows the number of items.
  2. In the product list, each card has an “Add to cart” button.
  3. On the cart page, you see the cart lines and the total.

In the old version, each part kept its own copy of the cart. A user added an item. The header badge said 3, but the cart page showed 2 items. After going to another page, the cart was sometimes completely empty.

Angular was not the problem. The problem was that nobody knew where the data lives and who changes it. In this lesson we look at the tools Angular gives you for this: components, signals, services and dependency injection.

Standalone components

Each piece of the page is a component: a TypeScript class with a template. Since Angular 19, every component is standalone by default. So you do not need an NgModule, and each component says itself what it needs.

import { Component, input, output } from '@angular/core';
import { CurrencyPipe } from '@angular/common';

export interface Product {
  id: number;
  name: string;
  price: number;
  inStock: boolean;
  sizes: string[];
}

@Component({
  selector: 'app-product-card',
  imports: [CurrencyPipe],
  template: `
    <h3>{{ product().name }}</h3>
    <p>{{ product().price | currency }}</p>
    <button [disabled]="!product().inStock" (click)="add.emit(product())">
      Add to cart
    </button>
  `,
})
export class ProductCard {
  product = input.required<Product>();
  add = output<Product>();
}
  1. The selector is the tag name other components write to use this component.
  2. The template is the component’s HTML. For a separate file, use templateUrl.
  3. The imports list names every component, pipe or directive the template uses. If you forget a component or a pipe, the compiler gives an error. If you forget a directive, it may silently do nothing.
  4. The class holds the component’s data and behavior. The template can only see members of the class.
The old syntax. In older code, components were declared inside an NgModule and inputs were written with the Input decorator. That code still works, but for new code use standalone components and the input function.

Template syntax

Four kinds of binding do almost all the work in a template:

Kind How you write it Direction Shop example
Interpolation Double curly braces around an expression Class to page, as text The product name
Property binding The property name in square brackets Class to a DOM property or a component input Disable the button when out of stock
Event binding The event name in parentheses Page to class A click on “Add to cart”
Two-way binding Parentheses inside square brackets Both ways The quantity of an item in the cart

For two-way binding, the child component uses the model function. A model value is both an input and an output:

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

@Component({
  selector: 'app-quantity',
  template: `
    <button (click)="value.set(value() - 1)" [disabled]="value() <= 1">-</button>
    <span>{{ value() }}</span>
    <button (click)="value.set(value() + 1)">+</button>
  `,
})
export class Quantity {
  value = model(1);
}
<!-- Parent template. qty is a signal in the parent: qty = signal(1) -->
<app-quantity [(value)]="qty" />
<p>You will buy {{ qty() }} items.</p>

When the user clicks the plus button, the child changes the model value. Because the binding is two-way, the parent’s signal gets the same value.

Control flow: @if, @for and @switch

Templates write conditions and loops with built-in blocks. These blocks are part of the template itself and need no import.

@if (cart.count() > 0) {
  <a routerLink="/cart">Cart ({{ cart.count() }})</a>
} @else {
  <span>Your cart is empty</span>
}

@for (p of products(); track p.id) {
  <app-product-card [product]="p" (add)="cart.add($event)" />
} @empty {
  <p>No products found.</p>
}

@switch (order().status) {
  @case ('paid') { <p>Paid. We are packing your order.</p> }
  @case ('shipped') { <p>Your order is on the way.</p> }
  @default { <p>Waiting for payment.</p> }
}
  1. The @if block can have @else if and @else.
  2. The @for block always needs a track expression. It tells Angular which item each row is. When the list is sorted or filtered, Angular only creates, moves or removes the rows it must.
  3. For track, pick a stable id like p.id. Using the row number ($index) is only safe for a list that is never sorted and never gets items added or removed.
  4. The @empty block shows when the list is empty.
The old syntax. Before these blocks, conditions and loops were written with the ngIf and ngFor directives (with a star before the name). You will see them in old code, but for new code use the @if and @for blocks.

Signals: data that tells you when it changes

A signal is a box around a value. When someone reads the value, Angular takes a note. When the value changes, Angular knows exactly what must update.

import { Injectable, computed, effect, signal } from '@angular/core';
import { Product } from './product-card';

export interface CartItem {
  productId: number;
  name: string;
  price: number;
  quantity: number;
}

@Injectable({ providedIn: 'root' })
export class CartService {
  private readonly items = signal<CartItem[]>([]);

  readonly lines = this.items.asReadonly();
  readonly count = computed(() => this.items().reduce((n, i) => n + i.quantity, 0));
  readonly total = computed(() => this.items().reduce((s, i) => s + i.price * i.quantity, 0));

  constructor() {
    // A side effect: keep a copy of the cart in the browser.
    effect(() => localStorage.setItem('cart', JSON.stringify(this.items())));
  }

  add(product: Product) {
    this.items.update(items => {
      const line = items.find(i => i.productId === product.id);
      return line
        ? items.map(i => (i === line ? { ...i, quantity: i.quantity + 1 } : i))
        : [...items, { productId: product.id, name: product.name, price: product.price, quantity: 1 }];
    });
  }
}
  1. The signal function makes a value you can change. To read it, call it like a function. To change it, use set or update.
  2. The computed function makes a derived value: the count and the total from the cart lines. It keeps the result and only computes again when one of the signals it read changes. You cannot write into it.
  3. The effect function is for side effects: saving to localStorage, sending a log, working with a non-Angular library. It runs a little after the change, not right away.
  4. The update method returns a new array. This matters: a signal compares the new value with the old one (with Object.is). If you change the same array and give it back, the signal thinks nothing changed and tells nobody.
items: signalThe cart linescount: computedNumber of itemstotal: computedThe total priceeffectSave in the browserHeader badgecart.count()Cart pagecart.total()The source: only written hereTemplates that read themArrow: where the change news goes
Signals form a graph. The cart lines are the source. The count and the total are built from them. Templates and the effect run again only when something they read changes.
Do not use effect to copy state. If an effect only sets one signal from another signal, it should be a computed. With an effect, the value is stale for a while, extra work happens, and anyone can break the copy.

Sometimes a value depends on another value, but the user must also be able to change it. For example, the selected size: it starts as the product’s first size, the user can pick another one, and when the product changes it must go back to the first size. For this case we have the linkedSignal function:

import { Component, input, linkedSignal } from '@angular/core';
import { Product } from './product-card';

@Component({
  selector: 'app-size-picker',
  template: `
    @for (s of product().sizes; track s) {
      <button [class.active]="s === size()" (click)="size.set(s)">{{ s }}</button>
    }
  `,
})
export class SizePicker {
  product = input.required<Product>();
  // Starts at the first size, resets when the product changes, and the user can set it.
  size = linkedSignal(() => this.product().sizes[0]);
}

Inputs, outputs and model

Parent and child talk with three functions:

  1. The input function makes an input. The result is a read-only signal, so you read it with parentheses in code and in the template. With input.required, the parent must give a value.
  2. The output function makes an output. The child tells with the emit method, and the parent listens with an event binding. The child does not change the parent’s data directly.
  3. The model function is an input you can write. When the child sets it, a parent with a two-way binding gets the new value.

The simple rule: data goes down, events go up. The product card does not know where the cart is. It only says “add this product”.

Services and dependency injection

Data that many parts of the page need, like the cart, goes in a service. Each component gets the service with the inject function:

import { Component, inject } from '@angular/core';
import { RouterLink } from '@angular/router';
import { CartService } from './cart.service';

@Component({
  selector: 'app-header',
  imports: [RouterLink],
  template: `<a routerLink="/cart">Cart ({{ cart.count() }})</a>`,
})
export class Header {
  protected readonly cart = inject(CartService);
}
  1. A service with providedIn set to root has one instance in the whole app. The header, the product list and the cart page see the same cart. The problem from the start of the lesson is now solved.
  2. If you list the service in a component’s providers, each instance of that component gets a new instance of the service. The component’s children see that same instance. When the component is destroyed, the service is destroyed too.
  3. When a component injects something, Angular starts at the component itself and walks up through its parents. The first provider it finds wins. If none has one, it reaches the root injector.
Root level: one instance for the appCartServiceAppHeaderCartPageProductPageImageGalleryGalleryState #1ImageGalleryGalleryState #2inject(CartService)Both get the same cart.Each gallery has its own instance.
The cart service is created once at the root and everyone shares it. The gallery state is in the gallery component's providers, so each gallery has its own instance.

When are component providers right? When each instance of the component needs its own state. For example, the product page has two image galleries, and each one has its own selected image:

import { Component, Injectable, inject, signal } from '@angular/core';

@Injectable()
export class GalleryState {
  readonly selected = signal(0);
}

@Component({
  selector: 'app-image-gallery',
  providers: [GalleryState], // one instance per gallery
  template: `<p>Image {{ state.selected() + 1 }}</p>`,
})
export class ImageGallery {
  protected readonly state = inject(GalleryState);
}

If you put the cart in a component’s providers like this, the cart is lost when the user leaves that page. This is a common mistake.

Routing and lazy loading

A user who only opens the home page does not need the checkout code. With loadComponent, each page’s code becomes a separate file (a chunk) that is only downloaded when the user goes to that page:

// app.routes.ts
import { Routes } from '@angular/router';
import { Home } from './home';

export const routes: Routes = [
  { path: '', component: Home },
  { path: 'products/:id', loadComponent: () => import('./product-page').then(m => m.ProductPage) },
  { path: 'cart', loadComponent: () => import('./cart-page').then(m => m.CartPage) },
  { path: 'checkout', loadComponent: () => import('./checkout').then(m => m.Checkout) },
];
// main.ts
import { bootstrapApplication } from '@angular/platform-browser';
import { provideRouter } from '@angular/router';
import { provideHttpClient } from '@angular/common/http';
import { App } from './app';
import { routes } from './app.routes';

bootstrapApplication(App, {
  providers: [provideRouter(routes), provideHttpClient()],
});

Inside one page, you can also delay heavy parts. Customer reviews are at the bottom of the product page. With the @defer block, the reviews component’s code is only downloaded when that part comes close to the screen:

<app-product-details [product]="product()" />

@defer (on viewport) {
  <app-reviews [productId]="product().id" />
} @placeholder {
  <p>Customer reviews</p>
}
  1. The @placeholder part shows until loading starts. The on viewport trigger watches this part to know when it is seen.
  2. If you write no trigger, the default is on idle: when the browser is idle.
  3. The component inside @defer must be standalone, and the same template must not use it outside the block. Otherwise it stays in the main bundle.
Initial bundleDownloaded at the startmain.ts + AppRouterHomeCartServiceA separate file per pageDownloaded when the user goes thereproduct-pagecart-pagecheckoutInside the product pageWhen the reviews part is seen@defer (on viewport)ReviewsDashed: downloaded later, and only if needed.
Only the code the home page needs is in the initial bundle. Other pages download when the user goes to them, and the reviews part when it is seen.

Common mistakes

Mistake Result The right way
An effect that only sets another signal The value is stale for a while. Extra work and renders. Use computed. If the user must also change it, use linkedSignal.
Changing an array or object inside a signal and setting the same object again Nobody is told. The page does not update. Return a new array or object with update.
The row number as track in a list that gets sorted Component state sticks to the wrong row. Extra DOM updates. A stable id like p.id.
A shared service in a component’s providers Each component has its own cart. The cart empties when the page changes. A shared service with providedIn set to root.
A child that changes the parent’s data directly Nobody knows who changed the data. The child tells with an output. The parent or a service changes the data.
Every page with component in the routes All code in the initial bundle. Slow start on phones. Use loadComponent and @defer.

Summary in 8 lines

  1. Every component is standalone and says in its imports what its template needs.
  2. A template has four kinds of binding: interpolation, property, event and two-way.
  3. Use @if, @for and @switch for conditions and loops. Track @for with a stable id.
  4. Data you change lives in a signal, derived values in computed, and side effects in effect.
  5. When a value comes from another value but the user can also change it, use linkedSignal.
  6. Data comes down with input. Events go up with output. The model function does both.
  7. A service with providedIn set to root has one shared instance. A service in a component’s providers is created again for each instance of that component.
  8. Load pages lazily with loadComponent and heavy parts with @defer.

Done reading this lesson?Mark it as finished so it shows in your lessons list and report card.