@for
block in Angular iterates over each item in a given collection and renders the content of a block repeatedly for each item.@for
block@for (item of items)
block is used to iterate over an array and render each product in a list <li>
item .$index
contextual property. We'll explore it in the next examples but here a preview:track
property uses the product.id
so we are sure that they are uniquecost
value next to the name
@for
display the list of items only when the Load button is clicked.@empty
block displays its content when the array is empty ([]
, null
, undefined
)products
signal contains an empty array@empty
block shows the Load button (since the array is empty)@for
block display the itemsproducts
array as empty ([]
). So, when clicked, the Load button is shown again@for
block to determine the element key to use in order to reduce Angular's work in DOM updates?trackBy
track
key
id
products
signal (the array of items), for example to calculate the total of items or a boolean to know if the array is empty or not:noItems()
: a boolean to know if the array is empty or nottotalItems()
: the length of the array@for
block iterates over the products array and tracks each item by its id.<li>{{item.name}}</li>
renders the name of each product in a list item.@empty
: displays a button if the products array is empty.<button>Load</button>
invokes the load()
method and populate the array@if(!noItems())
conditionally renders its content if noItems
is false
(i.e., there are items in the products array).{{products().length}}
displays the total number of items using products().length
.{{totalItems()}
works as the previous one but use a computed
signal instead (this is the preferred way since is more optimized and efficient)