The Angular Signals computed function is used to derive values from any number of signals.
Computed signal are read-only signals that derive their value from other signals.
We can define computed signals using the computed function and specifying a derivation. For instance:
firstName = signal('Signals');
lastName = signal('Test');
fullName = computed(() => this.firstName() + ' ' + this.lastName());
In the above example, changing the value of either firstName or lastName will automatically update the value of fullName.
What if we wanted fullName to update only when fistName changes but not when lastName changes?
The solution to that problem is a function called untracked:
fullNameUntracked = computed(() => this.firstName() + ' ' + untracked(() => this.lastName()));
The untracked function allows us to read the value of a signal without making such signal a dependency of our computed signal or effect.
A complete example is here 👉 https://stackblitz.com/edit/stackblitz-starters-yj8qak?file=src%2Fmain.ts
I hope you found it helpful. Thanks for reading. 🙏
Let's get connected! You can find me on:
- Medium: https://medium.com/@nhannguyendevjs/
- Dev: https://dev.to/nhannguyendevjs/
- Hashnode: https://nhannguyen.hashnode.dev/
- Linkedin: https://www.linkedin.com/in/nhannguyendevjs/
- X (formerly Twitter): https://twitter.com/nhannguyendevjs/
- Buy Me a Coffee: https://www.buymeacoffee.com/nhannguyendevjs
Top comments (2)
Hi Nhan Nguyen,
Your tips are very useful.
Thanks for sharing.
Thanks.