packages/lit-dev-content/site/tutorials/content/carousel/03.md
Now the selected property needs to actually do something. Use the
element's slot to manage the display of the selected item. Since only
elements assigned to slots render, assigning only the selected item will render
it and nothing else.
Update the render method to add the slot name.
<div class="fit">
<slot name="selected"></slot>
</div>
This sets the name attribute of the slot to selected so that only the
selected item is shown.
Now add the following below the render method.
{% switchable-sample %}
private previous = 0;
protected updated(changedProperties: PropertyValues) {
if (changedProperties.has('selected') && this.hasValidSelected()) {
this.updateSlots();
this.previous = this.selected;
}
}
private updateSlots() {
this.children[this.previous]?.removeAttribute('slot');
this.children[this.selected]?.setAttribute('slot', 'selected');
}
previous = 0;
updated(changedProperties) {
if (changedProperties.has('selected') && this.hasValidSelected()) {
this.updateSlots();
this.previous = this.selected;
}
}
updateSlots() {
this.children[this.previous]?.removeAttribute('slot');
this.children[this.selected]?.setAttribute('slot', 'selected');
}
{% endswitchable-sample %}
The updated method first checks if it needs to do any work, using the
changedProperties argument and the result of hasValidSelected().
If so, the updateSlots method sets the selected element's slot to selected.
Since the selected item is not rendered by Lit, it needs to be managed directly
with imperative code. The previously selected item is tracked so it can be
un-slotted when selected changes.
{% aside "warn" %}
In most cases, it's not recommended to directly manipulate element light DOM children.
Light DOM children are not part of an element's encapsulated Shadow DOM, and thus the user providing the light DOM children may make unforeseen manipulations to them that may undo your DOM modifications.
However, in this case the change being made to the selected item is
expressly related to the core purpose of the element. In addition, the slot
element has an
assign
method that removes the need to match the element's slot attribute to the
slot's name. However, at the time this tutorial has been authored, this isn't
yet widely supported so the code here sets the element's slot.
{% endaside %}
To verify that changing the selected item does what's expected,
open index.html and add a selected="1" attribute to the motion-carousel
element. Setting the attribute will also set the property and should show the
appropriate image.