Dzmitry Vasilevsky
Dzmitry Vasilevsky

Reputation: 1501

The difference between computed signal and getter in Angular

Signals is a cutting edge feature in Angular.
But the questions arouse what is the difference between

computed(() => `Result: ${this.someSignal()}`)

and

get someGetter () { return `Result: ${this.someSignal()}` }

First I thought that maybe getter won't be run when ChangeDetectionStrategy.OnPush is selected but that's not the case.

Here is an example where the both are working just the same https://stackblitz.com/edit/github-s2epxq?file=src%2Fmain.ts

So what is the difference and should we really prefer one before another?

Upvotes: 2

Views: 2121

Answers (1)

Matthieu Riegler
Matthieu Riegler

Reputation: 55669

You're getter doesn't return a signal, it is not reactive.

Only reactive node will be part of the reactivity tree and help Angular understand where a value changes and which component is impacted by it.

Also computed values get memoized, they would not get re-executed until one of their producers becomes dirty.

Upvotes: 2

Related Questions