<error-message>

💾 replit

// ⭐️ 1. custom web component
class ErrorMessage extends HTMLElement {

    // connected to document
    connectedCallback() {

        // attach shadow root (root == this.shadowRoot)
        let root = this.attachShadow({mode: 'open'});
        
        this.templates = root.appendTag('div');
        this.container = root.appendTag('div');

        // fill in templates
        this.templates.innerHTML = ErrorMessage.templates(); 
        
        // choose which template to use
        const kind = this.attr(`kind`);
        const template = this.templates.$(`template.${kind}-type`); 
        
        if (template) {
            const clone = template.content.cloneNode(true);
            this.container.append(clone); 
        }

    }

    // template HTML
    static templates() {

        // 3 templates
        // - template.warning-type
        // - template.error-type
        // - template.none-type
        return ` 
            <template class="warning-type">
                <style> 
                    .warning { 
                        background-color: yellow; 
                        padding: 15px; 
                        color: red; 
                    } 
                </style>

                <div class="warning">
                    <slot>Error component<slot> 
                </div> 
            </template>

            <template class="error-type">
                <style>
                    .error { 
                        background-color: red; 
                        padding: 15px; 
                        color: yellow; 
                    }
                </style>

                <div class="error">
                    <slot>Error component<slot> 
                </div> 
            </template>

            <template class="none-type">
                <style> 
                    .none { 
                        background-color: gray; 
                        padding: 15px; 
                        color: #eee; 
                    } 
                </style>

                <div class="none">
                    <slot>Error component<slot> 
                </div> 
            </template>
        `;
    }
} 

// ⭐️ 2. custom tag <error-message>
customElements.define('error-message', ErrorMessage);

Last updated