A signal is a value that tells Angular when it changes. This part covers signal, set, update and computed, why a plain field sometimes doesn’t update the screen, and a shopping cart built with signals.
A page that never changes is easy. Real pages change all the time: a counter goes up, a cart gets a new item, a timer ticks. Angular has to know when something changed, so it can update the screen. In Angular 22, the way you tell it is a signal.
This part covers signal(), set and update, reading signals in a template, computed() for values worked out from other values, and why the screen updates. In Part 2 we used double curly braces, [property] and (event) bindings. Here we put changing values behind them. Every example here is a whole file you can paste into your practice project from Part 1. Each one was built with Angular 22.3 and run in a browser before this was published.
Try this first
Paste this into src/app/app.ts. It keeps a count in an ordinary class field. One button adds one straight away. The other adds one a moment later, from a timer.
// src/app/app.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<p>Count: {{ count }}</p>
<button (click)="addOne()">Add one</button>
<button (click)="addOneLater()">Add one later</button>
`,
})
export class App {
protected count = 0;
protected addOne() {
this.count++;
}
protected addOneLater() {
setTimeout(() => this.count++, 100);
}
}
setTimeout(fn, 100) is plain JavaScript: it runs fn once, 100 milliseconds later.
Before you read on, guess. Click Add one later and wait a second. What does the page say? Then click Add one. What does it say now?
Here’s what happens. After Add one later and a short wait, the page shows:
Count: 0
Add oneAdd one later
The timer ran, and count is 1. The screen still says 0. Now click Add one. The page shows:
Count: 2
Add oneAdd one later
It jumped from 0 to 2. The 1 was there all along. Angular just didn’t know it had to draw it. (The two buttons show as Add oneAdd one later because buttons sit on one line, and the page text runs them together.)
Why the screen didn’t update
Angular doesn’t watch your fields. It can’t see this.count++ happen. It redraws a component only when something tells it the component might have changed. Angular calls that redraw change detection: it runs the template again, compares each value with the one it used last time, and updates the screen only where a value changed.
In a new Angular 22 project, two common things tell Angular to redraw a component:
- An event in its template, like the
(click)from Part 2. After your handler runs, Angular marks that component as needing a redraw. That’s why Add one worked, and why it also picked up the 1 the timer had left behind. - A signal that its template reads changes.
A timer is neither. When the setTimeout callback changed count, nothing told Angular, so nothing was redrawn. The same goes for anything else that happens outside a template event: a setInterval, a response from a server, a message from another part of the app.
You could try to remember which changes Angular hears about. It’s simpler to use a signal for every value that changes, and then the question goes away.
signal(): a value that says when it changes
Here’s the same page with a signal:
// src/app/app.ts
import { Component, signal } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<p>Count: {{ count() }}</p>
<button (click)="addOne()">Add one</button>
<button (click)="addOneLater()">Add one later</button>
`,
})
export class App {
protected readonly count = signal(0);
protected addOne() {
this.count.update((n) => n + 1);
}
protected addOneLater() {
setTimeout(() => this.count.set(this.count() + 1), 100);
}
}
Click Add one later and wait. This time the page shows:
Count: 1
Add oneAdd one later
Four things changed:
signal(0)makes a signal that holds 0. You importsignalfrom@angular/core.- You read a signal by calling it:
this.count(), and{{ count() }}in the template. The parentheses matter. We’ll see what happens without them below. set(value)replaces the value.update(fn)works out the new value from the old one.update((n) => n + 1)means “take the current value, call itn, and storen + 1“. It’s the same asset(this.count() + 1), but shorter and harder to get wrong.
When the template runs count(), Angular notes that this template read count. When count later changes, the signal tells Angular, and Angular schedules a redraw of every template that read it. The timer doesn’t need to know about Angular at all.
TypeScript works out the type from the starting value. signal(0) is a signal of numbers, so this.count.set('ten') won’t build. When the starting value doesn’t say enough, you give the type in angle brackets: signal<string[]>([]) is a signal holding a list of strings that starts empty. That’s called a generic, and we’ll use it in the cart example.
readonly and protected
Two small words go in front of the signal:
protectedkeepscountout of the class’s public API, while its template can still use it. Members that only the template needs areprotectedin modern Angular style.readonlymeans the field can’t be pointed at a different signal later. You still change the value withsetandupdate. What you can’t do is replace the whole signal withthis.count = signal(5). Anything that already read the old signal, like a computed, would keep following the old one and stop updating.
If you try, the build stops:
// src/app/app.ts
import { Component, signal } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<p>Count: {{ count() }}</p>
<button (click)="reset()">Reset</button>
`,
})
export class App {
protected readonly count = signal(0);
protected reset() {
this.count = signal(0);
}
}
✘ [ERROR] TS2540: Cannot assign to 'count' because it is a read-only property. [plugin angular-compiler]
To reset it, change the value: this.count.set(0).
Every signal in this series is readonly, and that’s the usual convention in Angular code.
Forgetting the parentheses
The most common slip with signals is leaving off the () in the template:
// src/app/app.ts
import { Component, signal } from '@angular/core';
@Component({
selector: 'app-root',
template: `<p>Count: {{ count }}</p>`,
})
export class App {
protected readonly count = signal(0);
}
That still builds, but ng serve prints a warning:
▲ [WARNING] NG8109: count is a function and should be invoked: count()}. Find more at https://v22.angular.dev/extended-diagnostics/NG8109 [plugin angular-compiler]
NG8109 is one of Angular’s extended diagnostics: checks for code that’s allowed but almost certainly wrong. (The stray } after count() is in Angular’s message, not a typo here.) The page shows:
Count: [Signal (count): 0]
That’s the signal’s own description of itself, not its value. Add the (), and read every ▲ [WARNING] line in the ng serve output. They’re usually real bugs.
computed(): values worked out from other values
Often one value depends on another. A total depends on the items in a cart. A doubled number depends on the number. You could store both and keep them in step by hand, but sooner or later you’d forget one. computed() works it out for you:
// src/app/app.ts
import { Component, computed, signal } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<p>{{ count() }} doubled is {{ double() }}. Again: {{ double() }}</p>
<button (click)="addOne()">Add one</button>
<button (click)="addThree()">Add three</button>
<button (click)="nothing()">Do nothing</button>
`,
})
export class App {
protected readonly count = signal(0);
protected readonly double = computed(() => {
console.log('computing double');
return this.count() * 2;
});
protected addOne() {
this.count.update((n) => n + 1);
}
protected addThree() {
this.count.update((n) => n + 1);
this.count.update((n) => n + 1);
this.count.update((n) => n + 1);
}
protected nothing() {}
}
computed takes a function. Angular runs it, remembers the result, and notes which signals it read. Here it reads count. A computed is a signal too: you read it by calling it, double().
We put a console.log inside, so we can see when the function really runs. Open the browser’s developer tools (F12) and look at the Console tab. When the page loads, it shows:
computing double
The template calls double() twice, but the function ran once. The second call got the remembered value. Now click Add one. The page shows:
1 doubled is 2. Again: 2
Add oneAdd threeDo nothing
and the console has one more line:
computing double
Now click Add three, then Do nothing twice. The console gets one more line, not three or five:
computing double
Here’s why. Add three changed count three times, but Angular doesn’t redraw after each change. It waits until your handler finishes and redraws once, and the template asks for double() once. Do nothing still causes a redraw, because it’s a click in the template. The template calls double() again, but count hasn’t changed since the last run, so double hands back the value it remembered.
So a computed is:
- cached: it remembers its result and reuses it until a signal it read changes;
- lazy: when a signal it read changes, it doesn’t run straight away. It runs the next time someone reads it.
You can’t set a computed. Its value always comes from its function. We’ll see the build error for that in a worked example below.
Watching a change flow through
This animation follows one click through the page above, with the template showing count() and double(). The dashed blue arrows mean “reads”.
A write marks what depends on it. Nothing is worked out until the render reads it.
Here are those steps in words, in case the animation doesn’t play for you:
- The page starts with
countat 0 anddoubleat 0. The template read both while it was drawn, anddoublereadcountwhile it was computed. Those reads are the dashed blue arrows. - You click Add one, and the handler calls
count.set(1).countnow holds 1. It tells everything that read it.doubleis only marked stale: it doesn’t recompute yet. The screen still shows 0. - Angular marks the component for a redraw and schedules a render for when your code has finished. If the handler changed
countthree more times, there would still be one render. - The render runs the template. The template calls
double().doublesees thatcountchanged, runs its function, and gets 2. Only the two texts that changed are updated on the screen.
Explain it like I’m ten
Picture the scoreboard at a school football game. Someone has to change the numbers on it.
A plain field is like a kid who scores a goal and writes the new score on a piece of paper in their pocket. The score is right, but the scoreboard doesn’t know. It only gets fixed when someone happens to walk over to the scoreboard for another reason. That’s what the Add one button did for our timer.
A signal is a score card with a bell on it. Whenever someone changes the card, the bell rings, and the person running the scoreboard knows to update it. Nobody has to run around checking every pocket.
A computed is a line on the scoreboard like “Home team leads by 2”. The operator doesn’t work it out every time a bell rings. They cross it out as “might be wrong now” and work it out again only when it’s time to show it.
The precise version
A signal holds a value and a list of who read it. When a template or a computed calls a signal, Angular records that read, because it’s happening inside something Angular is tracking. When you call set or update with a new value, the signal notifies everything on its list. A computed is marked dirty. A template’s component is marked for a redraw, and Angular schedules change detection to run once, after the current code finishes. During that run, the template calls double() again. double checks whether any signal it read has changed, recomputes if one has, and returns the cached value if not.
Where the analogy breaks: the bell doesn’t make the scoreboard change right away. Angular collects every change made by your code and redraws once at the end, so three bells in one click give one update. Also, a real scoreboard operator would update the “leads by” line even if nobody looked at it. A computed that nobody reads never runs at all.
computed only follows the signals it actually read
A computed doesn’t follow every signal in its function. It follows the ones it read the last time it ran. If a signal sits in a branch of an if that didn’t run, the computed doesn’t depend on it:
// src/app/app.ts
import { Component, computed, signal } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<p>{{ label() }}</p>
<button (click)="toggle()">Show age</button>
<button (click)="older()">Older</button>
`,
})
export class App {
protected readonly name = signal('Ana');
protected readonly age = signal(10);
protected readonly showAge = signal(false);
protected readonly label = computed(() => {
console.log('computing label');
return this.showAge() ? `${this.name()}, age ${this.age()}` : this.name();
});
protected toggle() {
this.showAge.update((show) => !show);
}
protected older() {
this.age.update((a) => a + 1);
}
}
The condition ? a : b is the short if from Part 2. The backticks make a template string, where ${...} puts a value into the text.
When the page loads, label runs once and logs one line. Click Older. age is now 11, but label didn’t read age last time, because showAge() was false. So nothing new is logged. Then click Show age, and Older again. The console shows these lines since the page loaded:
computing label
computing label
computing label
and the page shows:
Ana, age 12
Show ageOlder
The first line is the first render. The second is Show age: showAge changed, and this time the function read age too. The third is the second Older, which now counts. The first Older logged nothing, but it still counted: the age went from 10 to 12.
This is what you want. A computed does the least work it can, and it never shows a stale value, because a signal it didn’t read can’t change what it returned.
Don’t change a list in place
Signals decide whether something changed by comparing the old value with the new one. For a list or an object, that compares the reference: is it the same array, not does it hold the same items. If you push into the array that’s already in the signal, the signal still holds the same array, so it thinks nothing changed.
Here’s that mistake:
// src/app/app.ts
import { Component, computed, signal } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<ul>
@for (item of items(); track $index) {
<li>{{ item }}</li>
}
</ul>
<p>{{ total() }} items</p>
<button (click)="add()">Add pear</button>
`,
})
export class App {
protected readonly items = signal(['apple', 'bread']);
protected readonly total = computed(() => this.items().length);
protected add() {
this.items.update((list) => {
list.push('pear');
return list;
});
}
}
@for repeats a piece of template for each item in a list. Part 4 covers it; for now, read it as “one <li> per item”.
Click Add pear. The page shows:
apple
bread
pear
2 items
Add pear
The list says three things. The total says 2. The click marked the component for a redraw, so the @for ran again and found the pear in the array. But items never said it changed, so total kept its cached 2. If the push had happened in a timer, the list wouldn’t have shown the pear either.
The fix is to give the signal a new array. [...list, 'pear'] makes a new array with everything from list, then 'pear':
// src/app/app.ts
import { Component, computed, signal } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<ul>
@for (item of items(); track $index) {
<li>{{ item }}</li>
}
</ul>
<p>{{ total() }} items</p>
<button (click)="add()">Add pear</button>
`,
})
export class App {
protected readonly items = signal(['apple', 'bread']);
protected readonly total = computed(() => this.items().length);
protected add() {
this.items.update((list) => [...list, 'pear']);
}
}
Click Add pear, and the page shows:
apple
bread
pear
3 items
Add pear
The same rule goes for objects. To change one property, make a new object: user.update((u) => ({ ...u, name: 'Ben' })).
Setting the same value does nothing
The other side of that comparison: if you set a value that’s equal to the current one, the signal doesn’t notify anyone. For numbers, strings and booleans, “equal” means what you’d expect. (Angular uses Object.is, which is almost the same as ===.)
// src/app/app.ts
import { Component, computed, signal } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<p>{{ greeting() }}</p>
<button (click)="name.set('Ana')">Ana</button>
<button (click)="name.set('Ben')">Ben</button>
`,
})
export class App {
protected readonly name = signal('Ana');
protected readonly greeting = computed(() => {
console.log('computing greeting');
return `Hello, ${this.name()}`;
});
}
This time the handler is written right in the template: (click)="name.set('Ana')". That’s fine for one call.
Click Ana, then Ben, then Ben again. The console shows, since the page loaded:
computing greeting
computing greeting
One line for the first render and one for the change to Ben. Setting ‘Ana’ when it was already ‘Ana’ changed nothing, and neither did the second ‘Ben’.
Worked example: a shopping cart
Now let’s put these together. A shop has two products. You can add them to a cart and remove them again. The cart shows how many items it has and the total price, in whole dollars to keep the numbers simple.
// src/app/app.ts
import { Component, computed, signal } from '@angular/core';
interface CartItem {
id: number;
name: string;
price: number;
}
@Component({
selector: 'app-root',
template: `
<button (click)="add('Apple', 2)">Add apple</button>
<button (click)="add('Bread', 3)">Add bread</button>
<ul>
@for (item of items(); track item.id) {
<li>
{{ item.name }}: {{ item.price }}
<button (click)="remove(item.id)">Remove</button>
</li>
}
</ul>
<p>Items: {{ count() }}, total: {{ total() }}</p>
`,
})
export class App {
protected readonly items = signal<CartItem[]>([]);
protected readonly count = computed(() => this.items().length);
protected readonly total = computed(() =>
this.items().reduce((sum, item) => sum + item.price, 0),
);
private nextId = 1;
protected add(name: string, price: number) {
const item = { id: this.nextId++, name, price };
this.items.update((list) => [...list, item]);
}
protected remove(id: number) {
this.items.update((list) => list.filter((item) => item.id !== id));
}
}
Some things to notice:
interface CartItemis TypeScript. It describes the shape of an item: a numberid, a stringnameand a numberprice.signal<CartItem[]>([])then says the signal holds a list of those, starting empty.- Each item gets its own
id, so two apples are two different items.track item.idtells@forhow to tell items apart; Part 4 explains why that matters. addbuilds a new item and a new list.removeusesfilter, which also returns a new list: every item except the one with thatid.countandtotalare computed fromitems. They can never disagree with the list.reduceadds up the prices, starting from 0.nextIdis a plain field, and that’s fine. The template never shows it, so the screen doesn’t need to hear about it. It’sprivatebecause the template doesn’t use it either.
Click Add apple, Add bread and Add apple. The page shows:
Add appleAdd bread
Apple: 2 Remove
Bread: 3 Remove
Apple: 2 Remove
Items: 3, total: 7
Now click the first Remove. The page shows:
Add appleAdd bread
Bread: 3 Remove
Apple: 2 Remove
Items: 2, total: 5
We never told the count or the total to update. They follow items.
Worked example: a Clear button and a build error
Now we want a Clear button. A first try might be: the cart should be empty, so set the total and the count to 0.
// src/app/app.ts
import { Component, computed, signal } from '@angular/core';
interface CartItem {
id: number;
name: string;
price: number;
}
@Component({
selector: 'app-root',
template: `
<button (click)="add('Apple', 2)">Add apple</button>
<button (click)="clear()">Clear</button>
<p>Items: {{ count() }}, total: {{ total() }}</p>
`,
})
export class App {
protected readonly items = signal<CartItem[]>([]);
protected readonly count = computed(() => this.items().length);
protected readonly total = computed(() =>
this.items().reduce((sum, item) => sum + item.price, 0),
);
private nextId = 1;
protected add(name: string, price: number) {
const item = { id: this.nextId++, name, price };
this.items.update((list) => [...list, item]);
}
protected clear() {
this.total.set(0);
this.count.set(0);
}
}
ng serve refuses to build it:
✘ [ERROR] TS2339: Property 'set' does not exist on type 'Signal<number>'. [plugin angular-compiler]
src/app/app.ts:32:15:
32 │ this.total.set(0);
╵ ~~~
✘ [ERROR] TS2339: Property 'set' does not exist on type 'Signal<number>'. [plugin angular-compiler]
src/app/app.ts:33:15:
33 │ this.count.set(0);
╵ ~~~
Read it piece by piece:
TS2339is a TypeScript error code. It means “this property doesn’t exist on this type”. Search for the code if you meet one you don’t know.Property 'set' does not exist on type 'Signal<number>'names the property and the type.computed()returns aSignal<number>, a signal you can only read.signal()returns aWritableSignal<number>, which addssetandupdate.src/app/app.ts:32:15is the file, the line and the column. The~~~underlines the exact spot. (The real output starts the path with your project’s folder.)
The error is pointing at the real mistake. total and count aren’t values you store; they’re worked out from items. To empty the cart, empty items, and the computed values follow:
// src/app/app.ts
import { Component, computed, signal } from '@angular/core';
interface CartItem {
id: number;
name: string;
price: number;
}
@Component({
selector: 'app-root',
template: `
<button (click)="add('Apple', 2)">Add apple</button>
<button (click)="clear()">Clear</button>
<p>Items: {{ count() }}, total: {{ total() }}</p>
`,
})
export class App {
protected readonly items = signal<CartItem[]>([]);
protected readonly count = computed(() => this.items().length);
protected readonly total = computed(() =>
this.items().reduce((sum, item) => sum + item.price, 0),
);
private nextId = 1;
protected add(name: string, price: number) {
const item = { id: this.nextId++, name, price };
this.items.update((list) => [...list, item]);
}
protected clear() {
this.items.set([]);
}
}
Click Add apple twice. The page shows:
Add appleClear
Items: 2, total: 4
Click Clear, and it shows:
Add appleClear
Items: 0, total: 0
The same error shows up when you call set on a signal from asReadonly(). A writable signal’s asReadonly() gives you a read-only view of it. You’ll use it in Part 15, when a service keeps the writable signal private and hands out only the read-only one:
// src/app/app.ts
import { Component, signal } from '@angular/core';
@Component({
selector: 'app-root',
template: `<p>Count: {{ count() }}</p>`,
})
export class App {
private readonly countState = signal(3);
protected readonly count = this.countState.asReadonly();
}
The page shows:
Count: 3
Inside the class you change countState. Anything given count can read it but can’t set it.
In older code
Until recently, every Angular project loaded a library called zone.js. New Angular 22 projects don’t. It wrapped setTimeout, events, promises and network calls, so after any of them finished, Angular checked every component, and plain fields just worked. Most components were checked every time, a strategy now called Eager (it used to be called Default). To speed things up, people marked components changeDetection: ChangeDetectionStrategy.OnPush, which in Angular 22 is the default you don’t write. In OnPush code without signals you’ll see inject(ChangeDetectorRef) and calls to markForCheck() or detectChanges(), which tell Angular by hand that a component changed. A signal does that for you. Part 26 covers change detection in depth.
Best practices
- Use a signal for every value the template shows and that changes. Then the screen always updates, whatever changed it: a click, a timer or a server response. It replaces plain fields and remembering which changes Angular hears about.
- Use
computedfor anything worked out from other signals. It can’t get out of step, and it’s cached. It replaces storing a total and updating it by hand in every method. - Give a signal a new array or object. Write
update((list) => [...list, item]), notpush. A changed reference is how the signal knows something changed. - Mark signals
readonly, and template-only membersprotected.readonlystops the signal itself being replaced;protectedkeeps the template’s members out of the class’s public surface. - Prefer
updatewhen the new value depends on the old one.count.update((n) => n + 1)reads and writes in one step, instead ofcount.set(count() + 1).
Tips and traps
- Forgetting the parentheses.
{{ count }}builds with an NG8109 warning and shows the signal’s description instead of its value. Add the(). - A plain field that only sometimes updates. It works when a click in the same component changes it, and fails from a timer or a server response. It looks like a timing bug. The fix is a signal.
- Pushing into an array in a signal. The list may even look right after a click, while a computed from it shows an old number. Return a new array from
update. - Calling
seton a computed. The build fails with TS2339,Property 'set' does not exist on type 'Signal<...>'. Change the signals it’s computed from instead. - Side effects in a computed. A computed runs when someone reads it, maybe never, maybe after several changes at once. Don’t start a timer, save data or change another signal inside one. Keep it to working out a value. (Our
console.logcalls were there to watch it, not something to ship.) Part 8 coverseffect, the tool for side effects. - Expecting a log or a redraw for an unchanged value.
setwith the same number or string does nothing. That’s on purpose.
A signal tells Angular when it changes, and a computed works out its value only when someone reads it.
Exercises
Exercise 1. This page shows “Saving…” while it pretends to save, then should show “Saved”. Paste it, click Save and wait. It stays on “Saving…” forever. Why? Fix it.
// src/app/app.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<p>{{ status }}</p>
<button (click)="save()">Save</button>
`,
})
export class App {
protected status = 'Not saved';
protected save() {
this.status = 'Saving...';
setTimeout(() => (this.status = 'Saved'), 100);
}
}
Saving...
Save
Exercise 2. Write a component with a scores signal that starts as [3, 7], an Add 5 button that adds 5 to the list, and a computed best with the highest score. After one click, the page should show Scores: 3, 7, 5. Best: 7. Hint: list.join(', ') joins a list into text, and Math.max(...list) gives the largest number.
Exercise 3. Without running it, how many computing full name lines does this log after the page loads and you click Ana, then Lee, then Lee again? The page starts with “Ana Kim”.
// src/app/app.ts
import { Component, computed, signal } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<p>{{ fullName() }}</p>
<button (click)="first.set('Ana')">Ana</button>
<button (click)="last.set('Lee')">Lee</button>
`,
})
export class App {
protected readonly first = signal('Ana');
protected readonly last = signal('Kim');
protected readonly fullName = computed(() => {
console.log('computing full name');
return `${this.first()} ${this.last()}`;
});
}
Answers
1. status is a plain field. The click marks the component for a redraw, so “Saving…” appears. The timer then changes status to “Saved”, but a timer doesn’t tell Angular anything, so the screen keeps the old text. Make status a signal:
// src/app/app.ts
import { Component, signal } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<p>{{ status() }}</p>
<button (click)="save()">Save</button>
`,
})
export class App {
protected readonly status = signal('Not saved');
protected save() {
this.status.set('Saving...');
setTimeout(() => this.status.set('Saved'), 100);
}
}
Click Save and wait. The page shows:
Saved
Save
2. Add with a new array, and compute best from scores:
// src/app/app.ts
import { Component, computed, signal } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<p>Scores: {{ scores().join(', ') }}. Best: {{ best() }}</p>
<button (click)="addFive()">Add 5</button>
`,
})
export class App {
protected readonly scores = signal([3, 7]);
protected readonly best = computed(() => Math.max(...this.scores()));
protected addFive() {
this.scores.update((list) => [...list, 5]);
}
}
Click Add 5. The page shows:
Scores: 3, 7, 5. Best: 7
Add 5
3. Two lines. The first render logs one. Ana sets first to the value it already has, so nothing is notified. The first Lee changes last from Kim to Lee, so fullName runs again. The second Lee sets the same value again, so nothing happens. Here’s the run:
// src/app/app.ts
import { Component, computed, signal } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<p>{{ fullName() }}</p>
<button (click)="first.set('Ana')">Ana</button>
<button (click)="last.set('Lee')">Lee</button>
`,
})
export class App {
protected readonly first = signal('Ana');
protected readonly last = signal('Kim');
protected readonly fullName = computed(() => {
console.log('computing full name');
return `${this.first()} ${this.last()}`;
});
}
After the three clicks, the console shows:
computing full name
computing full name
and the page shows:
Ana Lee
AnaLee
What’s next
Our pages so far show one thing or another with a fixed template. In Part 4, we’ll use @if, @for with track, @switch and @let to show, hide and repeat parts of a template based on signals.