✅ What Are Web Components?
Web Components are a set of web platform APIs that allow you to create custom, reusable HTML elements with their own encapsulated functionality and styling, using native browser features.
🧩 Core Parts of Web Components:
- Custom Elements – Define your own HTML tags using
customElements.define(). - Shadow DOM – Encapsulation of HTML/CSS from the main document.
- HTML Templates – Define markup with
<template>and reuse it.
🧠 Example:
// Define a new custom element <my-button>
class MyButton extends HTMLElement {
connectedCallback() {
this.innerHTML = `<button>Click Me</button>`;
}
}
customElements.define('my-button', MyButton);
Usage:
<my-button></my-button>
🛠 How to Use Web Components in Frameworks:
👉 In React:
- React can render Web Components as if they are normal DOM elements.
- You must pass data using attributes or refs (not props).
function App() {
return <my-button></my-button>;
}
👉 In Angular:
- Angular supports Web Components out of the box.
- You can register them in
angular.jsonor viaCUSTOM_ELEMENTS_SCHEMA.
import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
@NgModule({
schemas: [CUSTOM_ELEMENTS_SCHEMA]
})
export class AppModule {}
✅ Why Use Web Components?
- Framework agnostic: usable across React, Angular, Vue, etc.
- Encapsulated and reusable.
- Ideal for design systems and micro frontends.