Web Components
Web Components is a collection of different technologies allowing developers to create reusable custom elements.
Technologies used in Web Components are
- Custom Elements — Create your own elements with a custom template(set of HTML elements) and functionality based on Javascript.
ex-
means user-defined tag which will render a defined template with functionality. - Shadow DOM — Used to make your custom elements isolated.
whenever you will create a custom element, it is always desirable to make it isolated so that its CSS and javascript can not be impacted by other CSS and javascript files.ex- if the custom element has a (any element you can take as ref.) element and it has or not some styling in your custom template but in your project, you have written some CSS(global CSS) like div{ color: red} then this will get applied to custom elementtoo unintentionally. So to avoid such vulnerabilities we must use Shadow Dom technology.
3. HTML templates( tag) — User-defined templates in HTML that aren’t rendered until called upon. You can create Web Components without it.
Lifecycle Hooks in Web Components
Lifecycle hook- Phases from Element created and destroyed in Dom. following lifecycle hooks are available for Web Components
- constructor()
The first thing that gets executed is the constructor. it is essentially called when the element is created in memory. - connectedCallback() it is the method that is executed when the element is attached to dom. So inside this method, you can do DOM-related operations.
- attributeChangedCallback(attrName, oldVal, newVal)
way to pass data to Custom Elements is via attributes, used for observing attribute update on the element.
ex then update it on scenario base like - disconnectedCallback() When the element is destroyed. Best place for cleanup.
Thanks for reading. Happy Coding 👏👏