lit/lit-element

Litelement Boolean property returns undefined in when not set

nchaitra opened this issue · 6 comments

We are using lit-element library for developing custom components. In that we are facing one issue when doing automation.
When we are setting boolean property the value will be true when boolean is set and undefined when removed.
This way it is different from native html button where we will get false when disabled is removed from button.

<my-button disabled></my-button>

when we run
document.querySelector('my-button').disabled
This returns true since disabled is set.
In automation tool it is shown as below when disabled is set
image

<my-button></my-button>
In automation tool it is shown as below when disabled is removed.

image

In this we will not see the disabled atribute itself when spying the button component.

Same issue is reported here as well for custom components.
https://www.ranorex.info/html-unary-attributes-how-to-identify-attribute-wi-t17059.html

Do you have any example code? How exactly did you declare the property?

Whole code is given

export class MyButton extends LitElement {
static get properties() {
return {
label: { type: String, reflect: true },
disabled: { type: Boolean, reflect: true }
};
}
static get styles() {
return [
css:host([disabled]) { opacity: 0.2; }
];
}

render() {
return html<div class="label">${this.label}</div> };
}
}
customElements.define('my-button', MyButton);

Do we have any solution for this?

I've same issue, then I just initialize it on class constructor

constructor() {
  super();
  this.disabled = false;
}

^ that's the correct solution. Lit doesn't initialize class fields, it just makes them reactive. In JavaScript a field in undefined until it's set.

As @justinfagnani mentioned, this is expected behavior and initializing the property is the right way to address it.