Search code examples
javascriptlit-elementlit-html

Can a lit-element track a variable outside its scope


In my lit-element I'm rendering something based on an outside variable. How can I know to update when that variable changes?

import { LitElement, html } from 'lit-element';
import './element01.js';

class Layout extends LitElement {
    createRenderRoot(){ return this; }

    static get properties() {
      return {
        settings: { Object }
      };
    }

    constructor() {
      super();
    }

    render() {
      return html`
        ${(settings.foo === 'bar')? html`<my-element01 />` : null}
      `;
    }
}
customElements.define('my-layout', Layout);

The settings object is being modified outside, how can this element know to update? I'm not using any other framework.


Solution

  • The index.html file should always have a

    <my-app></my-app>
    

    Within the my-app element, you will be able to use all the features of litElement such as

     class MyApp extends LitElement {
    
          static get properties() {
            return {
              prop: {type: Object},
            };
          }
    
          render() {
            return html`
            <my-element .prop="${this.prop}"</my-element>
            <my-server  .prop="${this.prop}"</my-server>
            <button @onClick='${(e) => this.prop += 1}' >change the settings value</button>
            `;
          }
        }