Created
May 2, 2020 05:42
-
-
Save justin-lyon/a937fcccbf55eba8b1f9caf23c05f544 to your computer and use it in GitHub Desktop.
an input number web component
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class NumberField extends HTMLElement { | |
static get observedAttributes () { | |
return [ 'label', 'value' ] | |
} | |
constructor () { | |
super() | |
const template = document.createElement('template') | |
template.innerHTML = ` | |
<label for="field"></label> | |
<input id="field" type="number" >` | |
this.attachShadow({ mode: 'open' }) | |
this.shadowRoot.appendChild(template.content.cloneNode(true)) | |
this._label = this.shadowRoot.querySelector('label') | |
this._input = this.shadowRoot.querySelector('input') | |
} | |
get label () { return this.getAttribute('label') } | |
get value () { return this.getAttribute('value') } | |
set label (val) { | |
console.log('setting label to', val) | |
this.setAttribute('label', val) | |
this.shadowRoot.querySelector('label').textContent = this.label | |
} | |
set value (val) { | |
console.log('setting value to', val) | |
this.setAttribute('value', Number(val)) | |
this.shadowRoot.querySelector('input').value = this.value | |
} | |
connectedCallback () { | |
if (!this.hasAttribute('label')) this.setAttribute('label', 1) | |
if (!this.hasAttribute('value')) this.setAttribute('value', 1) | |
} | |
attributeChangedCallback (name, oldValue, newValue) { | |
console.log(`${name} changed from ${oldValue} to ${newValue}`) | |
switch (name) { | |
case 'label': | |
this._label.textContent = this.label | |
break; | |
case 'value': | |
this._input.value = this.value | |
break; | |
} | |
} | |
} | |
customElements.define('c-number-field', NumberField) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment