AI Hints
Home›Angular Tutorial›computed(), effect() and Signals with Arrays
Angular · Lesson 33 of 120

Signals with Arrays

Lists that change.

⏱ 2 min read▶ Video at 40:01🎓 Free
Watch this lesson in the Angular courseWatch on YouTube ↗Full Angular course

Lists change too. Books are added to the basket, and removed. With signals, there's one rule to remember. Make a new array, don't change the old one.

  • Lists change
  • Add and remove
  • Make a new array

Change or replace?

Push changes the array in place, but the signal doesn't notice. Its box still holds the same array, so nothing is notified. Instead, update with a new array, using spread, filter, or slice. Then the signal knows something changed.

Don't

  • list().push(title)same arraynot notified

Do

  • update(l => [...l, title])a new arraynotified

A list of titles

Titles is a signal holding an array. Count is computed from its length. Add makes a new array, the old titles, plus the new one. Remove first makes a new array, without the first title. Hash box names the input, so the button can read its value. We add Circe, and then remove the first book. Run it. Dune was removed, Circe was added, and the count followed.

app.tstypescript
import { Component, signal, computed } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
    <input placeholder="Book title" #box>
    <button id="add" (click)="add(box.value); box.value = ''">Add</button>
    <button id="remove" (click)="removeFirst()">Remove first</button>
    <p>{{ count() }} books: {{ titles().join(', ') }}</p>
  `,
})
export class App {
  titles = signal(['Dune', 'Emma']);
  count = computed(() => this.titles().length);

  add(title: string) { this.titles.update(list => [...list, title]); }
  removeFirst() { this.titles.update(list => list.slice(1)); }
}
Also uses actions.json
[{"type": "input", "text": "Circe"}, {"click": "#add"}, {"click": "#remove"}]

Array recipes

To add, spread the old array, and add the new item. To remove, filter out what you don't want. To change one item, map over the array. Each of these returns a new array, so the signal notifies.

keyvalue
Add[...list, item]
Removelist.filter(x => x !== item)
Change onelist.map(x => ...)
All returna new array

Summary

Update array signals with a new array, using spread, filter, slice, or map. Never push into the old one. Next, signals with objects.

Key takeaways
  • [...list, item]
  • filter, slice, map
  • New array, new value
Next up: Signals with Objects — copy, then change