lit / lit-element

LEGACY REPO. This repository is for maintenance of the legacy LitElement library. The LitElement base class is now part of the Lit library, which is developed in the lit monorepo.
https://lit-element.polymer-project.org
BSD 3-Clause "New" or "Revised" License
4.49k stars 319 forks source link

Litelement Boolean property returns undefined in when not set #1210

Closed nchaitra closed 2 years ago

nchaitra commented 2 years ago

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

justinfagnani commented 2 years ago

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

nchaitra commented 2 years ago

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`

${this.label}
  }
`;

} } customElements.define('my-button', MyButton);

nchaitra commented 2 years ago

Do we have any solution for this?

DykiSA commented 2 years ago

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

constructor() {
  super();
  this.disabled = false;
}
justinfagnani commented 2 years ago

^ 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.

sorvell commented 2 years ago

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