Lit Element - After Attribute Change

02/27/2022, Sun
Categories: #JavaScript

Wait for DOM Change before Taking Action

Assume that we have a button which sets up with a click event listener to call upon a toggling of state to display an associated container:

import { LitElement, html } from "lit-element";

class MyElement extends LitElement {

  render() {
    return html`
      <button @click="${this._handleClick}">click</button>
      <div id="container" class=${this.open ? 'expanded' : 'collapsed'}>
        The contents.
      </div>
    `;
  }

  _handleClick() {
    this._toggleContainer();
  }

  //...
}

//...

The toggleContainer function will flip the attribute boolean value to change the class name for the container, but it is necessary to wait for the attribute change to propagate to the DOM before any further action can be taken by converting the operating function to be an await function.

// Add the async label for the function
async _toggleContainer() {

  // Change the property of the element
  this.open = !this.open;

  // Wait for the DOM change to complete.
  // The 'updateComplete' is a special built-in promise
  // that you will need to use for signaling completion.
  await this.updateComplete;

  // Perform other operations
  this.doOtherThings();
}