How to observe property changes with LitElement

grohjy picture grohjy · May 18, 2018 · Viewed 10.7k times · Source

I don't know how to observe property changes in LitElement.

I've been trying these methods, but I couldn't get these to work:

  static get properties() {
    return {
      temp1:String,
      temp2: {
       type:String,
       observer: '_temp2Changed'
        }
  };

  temp1Changed(newValue, oldValue){
    console.log("temp1 changed")
  }
  _temp2Changed(newValue, oldValue){
    console.log("temp2 changed")
  }

Answer

Michał Pietraszko picture Michał Pietraszko · Sep 22, 2018

Version 0.6.0+

First, you have to specify element properties. You can do it by creating a static getter which returns an object including their names as keys and their attribute related configuration.

The updated lifecycle method will be called when changed properties had caused a re-render. The first argument will return values before an update.

class MyComponent extends LitElement {
  static get properties() {
    return {
      foo: {}
    };
  }

  constructor() {
    super();
    this.foo = 0;
    setInterval(() => this.foo++, 1000);
  }

  updated(changedProperties) {
    console.log(changedProperties); // logs previous values
    console.log(this.foo); // logs current value
  }

  render() {
    return html`${this.foo}`;
  }
}

customElements.define("my-component", MyComponent);