Back to Lit

06

packages/lit-dev-content/site/tutorials/content/carousel/06.md

latest2.0 KB
Original Source

The slots need to be updated to correctly render the previous and currently selected items.

Add this code above the selected property accessor:

{% switchable-sample %}

ts
import {customElement, property, query} from 'lit/decorators.js';
...
export class MotionCarousel extends LitElement {
  @query('slot[name="selected"]', true)
  private selectedSlot!: HTMLSlotElement;

  @query('slot[name="previous"]', true)
  private previousSlot!: HTMLSlotElement;
  ...
js
get selectedSlot() {
  return (this.__selectedSlot ??=
    this.renderRoot?.querySelector('slot[name="selected"]') ?? null);
}

get previousSlot() {
  return (this.__previousSlot ??=
    this.renderRoot?.querySelector('slot[name="previous"]') ?? null);
}

{% endswitchable-sample %}

<ts-js> <span slot="ts">

The @query decorator provides convenient access to the slot elements. This will be used to see their currently assignedElements.

</span> <span slot="js">

querySelector provides convenient access to the slot elements. This will be used to see their currently assignedElements.

</span> </ts-js>

Find the updateSlots method and change it as follows:

{% switchable-sample %}

ts
private updateSlots() {
  // unset old slot state
  this.selectedSlot.assignedElements()[0]?.removeAttribute('slot');
  this.previousSlot.assignedElements()[0]?.removeAttribute('slot');
  // set slots
  this.children[this.previous]?.setAttribute('slot', 'previous');
  this.children[this.selected]?.setAttribute('slot', 'selected');
}
js
updateSlots() {
  // unset old slot state
  this.selectedSlot.assignedElements()[0]?.removeAttribute('slot');
  this.previousSlot.assignedElements()[0]?.removeAttribute('slot');
  // set slots
  this.children[this.previous]?.setAttribute('slot', 'previous');
  this.children[this.selected]?.setAttribute('slot', 'selected');
}

{% endswitchable-sample %}

The updateSlots method removes any currently assigned elements and then slots in the items for the previous and selected values.