Back to Lit

02

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

latest1.3 KB
Original Source

The carousel is now showing its first child item but there's no way to change what's displayed. It needs a selected property to control which item is shown.

Add the selected property accessor and accompanying code above the render method.

{% switchable-sample %}

ts
private selectedInternal = 0;
@property({type: Number})
selected = 0;

get maxSelected() {
  return this.childElementCount - 1;
}

hasValidSelected() {
  return this.selected >= 0 && this.selected <= this.maxSelected;
}

render() {
  if (this.hasValidSelected()) {
    this.selectedInternal = this.selected;
  }
  // ...
js
static properties = { selected: {type: Number} };

selectedInternal = 0;
constructor () {
  super();
  this.selected = 0;
}

get maxSelected() {
  return this.childElementCount - 1;
}

hasValidSelected() {
  return this.selected >= 0 && this.selected <= this.maxSelected;
}

render() {
  if (this.hasValidSelected()) {
    this.selectedInternal = this.selected;
  }
  // ...

{% endswitchable-sample %}

The user can set selected to any value, but it's only a valid selection if it's a number in the range of the total number of items in the carousel. The selectedInternal private property is clamped to this valid range and will be used in a later step.