Back to Lit

06

packages/lit-dev-content/site/tutorials/content/wc-to-lit/06.md

latest1.3 KB
Original Source

Attribute Bindings

Now, update the view when the rating attribute changes; this is similar to an input updating its view when you set <input value="newValue">. Luckily, the web component lifecycle includes the attributeChangedCallback. Update the rating by adding the following lines:

rating-element.<ts-js></ts-js>

{% switchable-sample %}

ts
static get observedAttributes() {
  return ['rating'];
}

attributeChangedCallback(attributeName: string, _oldValue: string, newValue: string) {
  if (attributeName === 'rating') {
    const newRating = Number(newValue);

    this.rating = newRating;
  }
}
js
static get observedAttributes() {
  return ['rating'];
}

attributeChangedCallback(attributeName, _oldValue, newValue) {
  if (attributeName === 'rating') {
    const newRating = Number(newValue);

    this.rating = newRating;
  }
}

{% endswitchable-sample %}

In order for the attributeChangedCallback to trigger, you must set a static getter for RatingElement.observedAttributes which declares which attributes should be observed for changes. You then set the rating attribute declaratively in the DOM. Give it a try:

index.html

html
<rating-element rating="5"></rating-element>

The rating should now be updating declaratively!