Render Lists of Item In LWC
To render a list of items, use for:each
the directive or the iterator
directive to iterate over an array. Add the directive to a nested <template>
tag that encloses the HTML elements you want to repeat.
The iterator
directive has first
and last
properties that let you apply special behaviors to the first and last items in an array.
Regardless of which directive you use, you must use a key
directive to assign a unique ID to each item. When a list changes, the framework uses key
to rerender only the item that changed. The key
in template is used for performance optimization and isn’t reflected in the DOM at run time.
for:each
When using the for:each
directive, use for:item="currentItem"
to access the current item. This example doesn’t use it, but to access the current item’s index, use for:index="index"
.
To assign a key to the first element in the nested template, use the key={uniqueId}
directive.
This example iterates over an array called contacts
, which is defined in the component’s JavaScript class.
iterator
To apply special behavior to the first or last item in a list, use the iterator
directive, iterator:iteratorName={array}
. Use the iterator
directive on a template
tag.
Use iteratorName
to access these properties:
value
—The value of the item in the list. Use this property to access the properties of the array. For example,iteratorName.value.propertyName
.index
—The index of the item in the list.first
—A boolean value indicating whether this item is the first item in the list.last
—A boolean value indicating whether this item is the last item in the list.
This sample code uses the same array as the previous example. To apply special rendering to the first and last items in the list, the code uses the first
last
properties with the if:true
directive.
If the item is first on the list, the <div>
tag renders with the styling defined in the CSS list-first
class. If the item is last on the list, the <div>
tag renders with the styling defined in the CSS list-last
class.
إرسال تعليق