Syed Saad Qamar
Software Engineer
at IOmechs
/SyedSaadQamar96
/in/syed-saad-qamar
/saadqamar01
/saadqamar96
What is Components?
What is Web Components?
Web components are based on three main specifications
The Custom Elements specification lays the foundation for designing and using new types of DOM elements.
class MyToolBar extends HTMLElement {
constructor() {
super();
...
}
...
}
window.customElements.define('my-tool-bar', MyToolBar);
<my-tool-bar></my-tool-bar>
Web components are based on three main specifications
The shadow DOM specification defines how to use encapsulated style and markup in web components.
HTML:
<div class="my-element">
</div>
<p>Regular element</p>
CSS:
p {
font-family: sans-serif;
color: green;
}
JS:
let myElement = document.querySelector('.my-element');
let shadow = myElement.attachShadow({
mode: 'closed'
});
shadow.innerHTML = `
<style>
p {
color: red;
}
</style>
<p>Element with Shadow DOM</p>
`;
Result:
Shadow Tree:
Web components are based on three main specifications
The template element holds HTML code without displaying it.
<template id="my-paragraph">
<style>
p {
color: white;
background-color: #666;
padding: 5px;
}
</style>
<p>My paragraph</p>
</template>
HTML:
<my-paragraph></my-paragraph>
JS:
customElements.define('my-paragraph',
class extends HTMLElement {
constructor() {
super();
let template = document.getElementById('my-paragraph');
let templateContent = template.content;
const shadowRoot = this.attachShadow({mode: 'open'})
.appendChild(templateContent.cloneNode(true));
}
})
Now we can use it by just adding it to our HTML document:
Now it's time to do some coding
Follow the following steps
2. Coping component file in the project
3. Add that file path in the script to the angular.json file
4. Add CUSTOM_ELEMENTS_SCHEMA in your module
Follow the following steps
2. Coping component file in the project
3. Add that file path in the script to the App.js