Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 74 ยท Signals and Reactivity

Signals in Components

Learn how to use Angular signals inside components - private state, read-only exposure, computed values, input(), model(), viewChild(), toSignal() and the mistakes to avoid.

Signals: signal, computed and effect introduced the three building blocks. This lesson puts them to work in a component. A modern Angular component keeps its changing data in signals, derives everything else with computed(), and receives data from its parent through signal-based inputs. The template then reads those signals like functions, and Angular knows exactly which parts of the page depend on which signal.

The goal is a small set of habits: one writable signal per piece of real state, computed() for everything that can be calculated from it, and a read-only public surface so that only the component itself can change its own state. You will also meet the signal-flavored APIs that replaced decorators: input(), model(), viewChild(), and the bridge toSignal().

What is real here. The Angular code in typescript and html blocks is real, but the site cannot run the Angular compiler, so those blocks are read-only. The runnable examples use a tiny hand-written signal implementation (about 40 lines) that mimics signal, computed and effect. It is a stand-in to show the ideas, not Angular's code: for example, its effects run synchronously right after a signal changes, while Angular schedules effects and batches them.

State lives in signals, derived values in computed

Here is a cart component in real Angular. The writable signal holds the only truth, the list of items. Count, total and summary are all derived, so they can never disagree with the list.

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

interface CartItem { name: string; price: number; qty: number }

@Component({
  selector: 'app-cart',
  template: `
    <p>{{ summary() }}</p>
    @for (item of items(); track item.name) {
      <li>{{ item.name }} x {{ item.qty }}</li>
    }
    <button (click)="add('Pen', 1.5)">Add a pen</button>
  `,
})
export class CartComponent {
  private readonly _items = signal<CartItem[]>([]);
  readonly items = this._items.asReadonly();

  readonly count = computed(() => this._items().reduce((n, i) => n + i.qty, 0));
  readonly total = computed(() => this._items().reduce((s, i) => s + i.price * i.qty, 0));
  readonly summary = computed(() => `${this.count()} items, $${this.total().toFixed(2)}`);

  add(name: string, price: number): void {
    this._items.update(list => [...list, { name, price, qty: 1 }]);
  }
}

Notice asReadonly(). A WritableSignal has set() and update(), so exposing it publicly lets any other class change the state. asReadonly() returns a view that can only be read. The convention of a private _items plus a public items is common, and it keeps every change inside methods like add() where you can validate it.

The next example runs the same idea with the stand-in signals. The effect plays the role of the template: it re-runs whenever something it read has changed.

TypeScript A component's state, derived values and a render effect

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.

You see four renders, one at start and one per add(), because each call produces a new array and therefore a new value. Every change builds a new array with [...list, x] or map() rather than editing the old one; the reason is explained below. The commented-out line would be a compile error, which is exactly what you want from a read-only surface.

flowchart LR
  items["items signal<br/>(real state)"] --> count["count computed"]
  items --> total["total computed"]
  count --> summary["summary computed"]
  total --> summary
  summary --> view["template / effect"]
  items --> view

Only items is written to. Everything to its right is recalculated lazily when read.

Signal-based inputs: input() and model()

Data arriving from a parent is also a signal. input() declares a read-only signal that Angular fills from the parent's template binding; input.required<T>() has no default and makes the binding mandatory. model() declares a writable signal that can flow both ways, which is what [(value)] two-way binding uses. Inputs and Outputs covers the full syntax; here is the shape.

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

@Component({
  selector: 'app-rating',
  template: `
    <button (click)="value.set(value() - 1)">-</button>
    <span>{{ stars() }}</span>
    <button (click)="value.set(value() + 1)">+</button>
  `,
})
export class RatingComponent {
  readonly max = input(5);              // InputSignal<number>, read-only for the child
  readonly label = input.required<string>();
  readonly value = model(0);            // ModelSignal<number>, writable and bindable

  readonly stars = computed(() => '*'.repeat(this.value()).padEnd(this.max(), '.'));
}
HTML
<app-rating label="Quality" [max]="10" [(value)]="score" />

Because max is an input signal, the child cannot call max.set(): a parent owns that value. value is a model, so when the child calls value.set(4) the parent's score is updated too. Since stars is a computed(), it recomputes whenever either the parent changes max or the child changes value, with no ngOnChanges required.

This stand-in wires a model to a parent signal with two effects, one in each direction. The Object.is check inside set() is what stops the two effects from ping-ponging forever.

TypeScript Input is one way, model is two way

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 output shows the value following the change wherever it started: setting the child's model updates the parent's score, setting the parent's score updates the child, and a new max re-derives stars. The stand-in is deliberately crude, since real Angular compiles the binding rather than using effects, but the data flow it shows is the same.

viewChild() and toSignal()

Two more APIs produce signals. viewChild() replaces the @ViewChild decorator: it returns a signal holding the matching element or component, and the signal is undefined until the view has rendered, so read it in a computed() or effect(), not in the constructor. viewChild.required() throws if nothing matches. See Template Refs, View Queries and Host Bindings for the details.

toSignal() converts an RxJS Observable into a signal. It subscribes for you and unsubscribes when the component is destroyed. Because a signal always has a value, you give it an initialValue, or the signal's type includes undefined.

TypeScript
import { Component, computed, viewChild, ElementRef, inject } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { ActivatedRoute } from '@angular/router';
import { map } from 'rxjs';

@Component({
  selector: 'app-product-page',
  template: `
    <h1 #title>Product {{ id() }}</h1>
    <p>Title element is ready: {{ hasTitle() }}</p>
  `,
})
export class ProductPageComponent {
  private readonly route = inject(ActivatedRoute);

  readonly id = toSignal(this.route.paramMap.pipe(map(p => p.get('id'))), { initialValue: null });

  private readonly title = viewChild<ElementRef<HTMLElement>>('title');
  readonly hasTitle = computed(() => this.title() !== undefined);
}

Signals and RxJS Interop goes further, including the reverse direction with toObservable().

Patterns and anti-patterns

A few rules keep signal code healthy.

  • Derive, do not copy. If a value can be calculated from other signals, make it a computed(). Copying it into a second writable signal from an effect() creates two sources of truth and extra work.
  • Update immutably. Signals decide whether something changed with Object.is. Pushing into an array that is already in a signal keeps the same array identity, so nothing is notified. Replace the array with a new one.
  • Keep computed pure. A computed() should only read and return. Writing to a signal inside it throws an error, and logging or calling the network there is a smell.
  • Effects are for the outside world. Use effect() for things like logging, analytics or syncing to localStorage, not for calculating state.
  • Read with parentheses. In a template, {{ count }} shows the function itself, while {{ count() }} shows the value and registers the dependency.

The last runnable example proves the first two rules with counters.

TypeScript Why computed beats an effect, and why mutation is invisible

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 effect copy re-ran as soon as price changed even though nobody needed the result yet. The computed value did not calculate at all until it was read, and reading it twice cost one calculation thanks to memoization. And the pushed number is in the array, but the effect never learned about it, because the signal still held the same array object.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why expose a signal with asReadonly() instead of making the writable signal public?

    asReadonly() returns a view that can be read but not written. That keeps all changes inside methods where the component can validate them.
  2. 2. What does the child component's input() signal allow the child to do?

    input() creates a read-only signal filled by the parent's binding. For a value the child can also change, use model().
  3. 3. A signal holds an array. You call items().push(4). What happens to computed values and effects that read the signal?

    Signals compare values with Object.is. The same array identity means no change was detected, so replace the array with items.update(list => [...list, 4]).
  4. 4. Why does toSignal(observable) usually need an initialValue?

    Without an initialValue, the signal's type includes undefined until the first emission, since a signal can always be read.
  5. 5. Which is the better way to keep a total in step with price and quantity signals?

    A computed value has one source of truth, is calculated lazily and is memoized. An effect copy duplicates state and runs eagerly.

Summary

  • Keep real state in signal(), derive everything else with computed(), and use effect() only for side effects outside the component.
  • Expose state with asReadonly() and change it through methods.
  • input() is a read-only signal filled by the parent, input.required() is mandatory, and model() is writable and supports [(value)].
  • viewChild() gives a signal that is undefined until the view exists; toSignal() turns an Observable into a signal and cleans up for you.
  • Update arrays and objects immutably, and read signals with parentheses.

Next: linkedSignal, resource and httpResource.