docs: https://angular.io/guide/signals
Let's work on creating a new property to display the last item in a list using Angular's computed property.
First, ensure that computed
is imported from angular-core
:
In the component export, provide a function to computed
that you want to be invoked every time we refresh the page. Let's supply it with a function that grabs the last item from our items
array:
Here, we use Array.prototype.slice()
to create a copy of our items
array, then use Array.prototype.pop()
on the copied array to grab the last item. We use a copy of our array to avoid mutating our original items
array.
Now that our computed
property is ready, we need to actually use it.
We'll do so within our for loop in the template. Replace the current item with a call to lastItem()
:
You'll find that the application is now only displaying the final item in the items
array - in our case, "Charlie":
And that's it! We've successfully used an Angular computed property.