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
:
1import { computed } 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:
1lastItem = computed(() =>
2 this. items.slice());
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()
:
1@for (item of lastItem(); track 'id') {
2 <li>{{item.name}}</li>
3}
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.
Transcript
A new property, we'll just display the last item and use Angular computed. So make sure that the computed is actually imported from Angular core and provide a function which will be invoked every time that you want to refresh our page. So items dot slice, and we will basically take the last item. Our computed is ready but we need to make actual use of that so we will call last item in the for loop and we will see that our application is actually displaying only Charlie and we can see that our computed is listed over here.