Search code examples
polymerlit-element

How to observe property changes with LitElement


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")
  }

Solution

  • I found a solution from Polymer's PWA Starter kits.

    Add following to your element definition:

    _propertiesChanged(props, changed, oldProps) {
        console.log("_propertiesChanged(props, changed, oldProps):");
        console.log(props);    
        console.log(changed);  
        console.log(oldProps); 
        if (changed && 'temp1' in changed) {
          console.log("if temp1:"+changed.temp1);
        }
        super._propertiesChanged(props, changed, oldProps); //This is needed here
    }
    
    console output:
    _propertiesChanged(props, changed, oldProps):
    {temp1: "newVal1", temp2: "val2"}
    {temp1: "newVal1"}
    {temp1: "val1"}
    if temp1:newVal1