<error-message>
Last updated
Last updated
// โญ๏ธ 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);
<!-- web components -->
<error-message kind="none">"none" error message</error-message>
<error-message kind="warning">this is a warning</error-message>
<error-message kind="error">this is an error message</error-message>
<!-- scripts -->
<script src="helpers.js"></script>
<script src="script.js"></script>
helpers.js ๐ JS ๅธธ็จๅฝๆธ