javascripthtmlweb-componentcustom-element

Web Component attributeChangedCallback not called for DISABLED attribute


How can my custom-element / web-component detect a DISABLED attribute change?

static get observedAttributes() {
    return ['checked', 'disabled', 'value'];
}

My attributeChangedCallback() is not called?


Solution

  • You can declare disabled as getter/setter property on your Web Component

    For the elements that do not have a disabled property by default:
    https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/disabled

    <my-element disabled  ></my-element>
    <script>
      function log(...args) {
        console.log(...args)
      }
      customElements.define('my-element',
        class extends HTMLElement {
          static get observedAttributes(){
            return ["disabled"];
          }
          attributeChangedCallback(name, oldValue, newValue){
           log("attributeChanged",name,oldValue,newValue)
          }
          connectedCallback() {
            log("connectedCallback");
            this.disabled  = !this.disabled;
          };
          get disabled(){
            log("GET disabled", this.hasAttribute("disabled"));
            return this.hasAttribute("disabled");
          }
          set disabled(v){
            log("SET disabled", v);
            this.toggleAttribute("disabled",v);
          }
        });
    </script>