Solution 2: Intégrer le pattern ARIA sur l'host
<p id="info">Remplissez le formulaire et cliquez sur le bouton pour envoyer le formulaire</p>
<my-button aria-describedby="info">Envoyer</my-button>
<template id="mg-button-template">
<slot></slot>
</template>
<script>
class MyButton extends HTMLElement {
constructor() {
super();
const template = document.getElementById('mg-button-template');
const content = template.content.cloneNode(true);
this.attachShadow({ mode: 'open' });
shadow.appendChild(content);
}
connectedCallback() {
this.setAttribute('role', 'button');
if (!this.hasAttribute('tabindex')) {
this.setAttribute('tabindex', '0');
} else if (this.hasAttribute('disabled')) {
this.setAttribute('tabindex', '-1');
}
const desc = this.shadowRoot.querySelector('#info');
if (this.hasAttribute('description')) {
desc.textContent = this.getAttribute('description');
this.setAttribute('aria-describedby', 'info');
}
this.addEventListener('keydown', e => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
this.click();
}
});
}
}
customElements.define('my-button', MyButton);
</script>