SlideShare ist ein Scribd-Unternehmen logo
1 von 74
Downloaden Sie, um offline zu lesen
WEB COMPONENTSEVERYWHERE
A B O U T M E
{
"name": "Ilia Idakiev",
"experience": [
"Developer & Founder of HNS/HG",
"Lecturer in Advanced JS @ Soa University",
"Contractor / Consultant",
"Public / Private Courses"
],
"involvedIn": [
"Angular Soa", "SoaJS", "BeerJS",
]
}
WEB COMPONENTS EVERYWHERE
SEPARATION OF CONCERNS (SOC)
▸ Design principle for separating a computer program into distinct sections, such
that each section addresses a separate concern. (Modularity)
WEB COMPONENTS EVERYWHERE
S.O.L.I.D PRINCIPLES OF OBJECT-ORIENTED PROGRAMMING
▸ Single Responsibility Principle
▸ Open / Close Principle
▸ Liskov Substitution Principle
▸ Interface Segregation Principle
▸ Dependency Inversion Principle
http://aspiringcraftsman.com/2011/12/08/solid-javascript-single-responsibility-principle/
WEB COMPONENTS EVERYWHERE
WEB COMPONENTS
▸ Introduced by Alex Russell (Chrome team @ Google) 

at Fronteers Conference 2011
▸ A set of features currently being added by the W3C to
the HTML and DOM specications that allow the creation of
reusable widgets or components in web documents and web applications.
▸ The intention behind them is to bring component-based software
engineering to the World Wide Web.
WEB COMPONENTS EVERYWHERE
WEB COMPONENTS FEATURES:
▸ HTML Templates - an HTML fragment is not rendered, but stored until it is
instantiated via JavaScript.
▸ Shadow DOM - Encapsulated DOM and styling, with composition.
▸ Custom Elements - APIs to define new HTML elements.
▸ HTML Imports - Declarative methods of importing HTML documents into other
documents. (Replaced by ES6 Imports).
DEMOTHE NATIVE WAY
WEB COMPONENTS EVERYWHERE
DEFINE CUSTOM ELEMENT
(function () {
const template = createTemplate('<div>Hello World<div>');
class Counter extends HTMLElement {
constructor() {
super();
const shadowRoot = this.attachShadow({ mode: 'open' });
shadowRoot.appendChild(template.content.cloneNode(true));
}
}
customElements.define('hg-counter', Counter);
}());
Create an isolated scope
counter.js
WEB COMPONENTS EVERYWHERE
(function () {
const template = createTemplate('<div>Hello World<div>');
class Counter extends HTMLElement {
constructor() {
super();
const shadowRoot = this.attachShadow({ mode: 'open' });
shadowRoot.appendChild(template.content.cloneNode(true));
}
}
customElements.define('hg-counter', Counter);
}());
DEFINE CUSTOM ELEMENT Create a new class that extends HTMLElement
counter.js
WEB COMPONENTS EVERYWHERE
(function () {
const template = createTemplate('<div>Hello World<div>');
class Counter extends HTMLElement {
constructor() {
super();
const shadowRoot = this.attachShadow({ mode: 'open' });
shadowRoot.appendChild(template.content.cloneNode(true));
}
}
customElements.define('hg-counter', Counter);
}());
DEFINE CUSTOM ELEMENT Register the new custom element.
counter.js
WEB COMPONENTS EVERYWHERE
HTML TEMPLATES
▸ The <template> tag holds its content hidden from the client.
▸ Content inside a <template> tag will be parsed but not rendered.
▸ The content can be visible and rendered later by using JavaScript.
WEB COMPONENTS EVERYWHERE
WAYS TO CREATE A TEMPLATE
<template id="template">
<h2>Hello World</h2>
</template>
const template =
document.createElement('template');
template.innerHTML =
'<h2>Hello World</h2>';
Using HTML Using JavaScript
WEB COMPONENTS EVERYWHERE
CREATE TEMPLATE HELPER FUNCTION
function createTemplate(string) {
const template = document.createElement('template');
template.innerHTML = string;
return template;
}
utils.js
WEB COMPONENTS EVERYWHERE
CREATE THE TEMPLATE
(function () {
const template = createTemplate('<div>Hello World<div>');
class Counter extends HTMLElement {
constructor() {
super();
const shadowRoot = this.attachShadow({ mode: 'open' });
shadowRoot.appendChild(template.content.cloneNode(true));
}
}
customElements.define('hg-counter', Counter);
}());
Use the create template helper function.
counter.js
WEB COMPONENTS EVERYWHERE
SHADOW DOM
▸ Isolated DOM - The component's DOM is self-contained
(e.g. document.querySelector() won't return nodes in the component's shadow DOM).
▸ Scoped CSS - CSS defined inside shadow DOM is scoped to it. Style rules
don't leak out and page styles don't bleed in.
▸ Composition - done with the <slot> element.

(Slots are placeholders inside your component that users can ll with their own markup).
WEB COMPONENTS EVERYWHERE
DEFINE CUSTOM ELEMENT
(function () {
const template = createTemplate('<div>Hello World<div>');
class Counter extends HTMLElement {
constructor() {
super();
const shadowRoot = this.attachShadow({ mode: 'open' });
shadowRoot.appendChild(template.content.cloneNode(true));
}
}
customElements.define('hg-counter', Counter);
}());
counter.js
Utilise the class constructor.
WEB COMPONENTS EVERYWHERE
ATTACH SHADOW DOM
(function () {
const template = createTemplate('<div>Hello World<div>');
class Counter extends HTMLElement {
constructor() {
super();
const shadowRoot = this.attachShadow({ mode: 'open' });
shadowRoot.appendChild(template.content.cloneNode(true));
}
}
customElements.define('hg-counter', Counter);
}());
Attach the shadow DOM.
counter.js
WEB COMPONENTS EVERYWHERE
(function () {
const template = createTemplate('<div>Hello World<div>');
class Counter extends HTMLElement {
constructor() {
super();
const shadowRoot = this.attachShadow({ mode: 'open' });
shadowRoot.appendChild(template.content.cloneNode(true));
}
}
customElements.define('hg-counter', Counter);
}());
CREATE THE TEMPLATE Attach the template contents to the shadow root.
counter.js
WEB COMPONENTS EVERYWHERE
USE OUR CUSTOM ELEMENT
<body>
<hg-counter></hg-counter>
<script src="./util.js"></script>
<script src="./counter.js"></script>
</body>
index.html
WEB COMPONENTS EVERYWHERE
EXTEND OUR CUSTOM ELEMENT
index.html
(function () {
const template = createTemplate(`
<div name="value"></div>
<button data-type=“dec">-</button>
<button data-type="inc">+</button>
`);
class Counter extends HTMLElement {
constructor() {
super();
WEB COMPONENTS EVERYWHERE
EXTEND OUR CUSTOM ELEMENT
index.html
constructor() {
super();
const shadowRoot = this.attachShadow({ mode: 'open' });
shadowRoot.appendChild(template.content.cloneNode(true));
shadowRoot.addEventListener('click', ({ target }) => {
const type = target.getAttribute('data-type');
if (type === 'dec') {
this.counter--;
} else if (type === 'inc') {
this.counter++;
}
});
WEB COMPONENTS EVERYWHERE
UPDATING THE DOM
utils.js
function updateDOM(root, updates) {
updates.forEach(item => {
root.querySelectorAll(`[name=${item.name}]`).forEach(element =>
element.textContent = item.value
);
});
}
WEB COMPONENTS EVERYWHERE
EXTEND OUR CUSTOM ELEMENT
index.html
class Counter extends HTMLElement {
set counter(value) {
this._counter = value;
}
get counter() {
return this._counter;
}
constructor() {
super();
const shadowRoot = this.attachShadow({ mode: 'open' });
shadowRoot.appendChild(template.content.cloneNode(true));
this.counter = 0;
WEB COMPONENTS EVERYWHERE
EXTEND OUR CUSTOM ELEMENT
index.html
class Counter extends HTMLElement {
constructor() {
super();
const shadowRoot = this.attachShadow({ mode: 'open' });
shadowRoot.appendChild(template.content.cloneNode(true));
this.counter = 0;
this._update = () => {
updateDOM(shadowRoot, [{
name: 'value',
value: this.counter
}]);
}
WEB COMPONENTS EVERYWHERE
EXTEND OUR CUSTOM ELEMENT
index.html
class Counter extends HTMLElement {
set counter(value) {
this._counter = value;
this._update();
}
get counter() {
return this._counter;
}
constructor() {
super();
const shadowRoot = this.attachShadow({ mode: 'open' });
shadowRoot.appendChild(template.content.cloneNode(true));
this.counter = 0;
WEB COMPONENTS EVERYWHERE
CUSTOM COMPONENT ATTRIBUTES
index.html
<body>
<hg-counter value="10"></hg-counter>
<script src="./util.js"></script>
<script src="./counter.js"></script>
</body>
WEB COMPONENTS EVERYWHERE
CUSTOM ELEMENTS LIFECYCLE CALLBACKS
▸ connectedCallback - Invoked each time the custom element is appended into a
document-connected element. This will happen each time the node is moved, and
may happen before the element's contents have been fully parsed.
▸ disconnectedCallback - Invoked each time the custom element is disconnected
from the document's DOM.
▸ attributeChangedCallback - Invoked each time one of the custom element's
attributes is added, removed, or changed.
▸ adoptedCallback - Invoked each time the custom element is moved to a new
document.
WEB COMPONENTS EVERYWHERE
CUSTOM COMPONENT ATTRIBUTES
index.html
class Counter extends HTMLElement {
static get observedAttributes() {
return ['value'];
}
attributeChangedCallback(name, oldValue, newValue) {
if (name === 'value') {
this.counter = newValue;
}
}
constructor() {
Handle attribute changes
WEB COMPONENTS EVERYWHERE
CUSTOM COMPONENT ATTRIBUTES
index.html
class Counter extends HTMLElement {
static get observedAttributes() {
return ['value'];
}
attributeChangedCallback(name, oldValue, newValue) {
if (name === 'value') {
this.counter = newValue;
}
}
constructor() {
Dene which attributes should be watched
WHAT ABOUT STYLES?
WEB COMPONENTS EVERYWHERE
CUSTOM COMPONENT STYLES
index.html
Apply scoped styles to our component
(function () {
const template = createTemplate(`
<style>
:host {
display: flex;
}
div[name="value"] {
min-width: 30px;
}
</style>
<div name="value"></div>
<button data-type="dec">-</button>
<button data-type="inc">+</button>
`);
class Counter extends HTMLElement {
WEB COMPONENTS EVERYWHERE
WEB COMPONENT CSS
▸ :host - selects the shadow host of the shadow DOM
▸ :host() - match only if the selector given as the function's parameter matches
the shadow host.
▸ :host-context() -  match only if the selector given as the function's parameter
matches the shadow host's ancestor(s) in the place it sits inside the DOM
hierarchy.
▸ ::slotted() - represents any element that has been placed into a slot inside an
HTML template
WHAT ABOUT
DISPATCHING EVENTS?
WEB COMPONENTS EVERYWHERE
CUSTOM EVENTS Dispatching custom event
const test = shadowRoot.getElementById('element-button');
test.addEventListener('click', () => {
this.dispatchEvent(new CustomEvent('toggle', {
detail: {
value: true
}
}))
});
custom-element.js
WEB COMPONENTS EVERYWHERE
CUSTOM EVENTS Listening for custom event
• CustomEvent {isTrusted: false, detail: {value: true}, type: "toggle", …}
const el = document.getElementById('my-custom-element');
el.addEventListener('toggle', e => {
console.log(e);
});
main.js
Console
WEB COMPONENTS EVERYWHERE
FURTHER READING
▸ Extending different HTML Elements

(e.g. HTMLButton)
WEB COMPONENTS EVERYWHERE
BENEFITS OF USING CUSTOM COMPONENTS
▸ Framework agnostic - Written in JavaScript and native to the browser.
▸ Simplifies CSS - Scoped DOM means you can use simple CSS selectors, more
generic id/class names, and not worry about naming conflicts.
• Productivity - Think of apps in chunks of DOM rather than one large (global) page.
▸ Productivity - Think of apps in chunks of DOM rather than one large (global)
page.
WEB COMPONENTS EVERYWHERE
BROWSER SUPPORT
WEB COMPONENTS EVERYWHERE
COSTS OF USING CUSTOM COMPONENTS
▸ Template Generation - manually construct the DOM for our templates 

(No JSX features or Structural Directives)
▸ DOM Updates - manually track and handle changes to our DOM

(No Virtual DOM or Change Detection)
WEB COMPONENTS EVERYWHERE
LIT HTML
▸ Library Developed by the Polymer Team @ GOOGLE
▸ Efficient - lit-html is extremely fast. It uses fast platform features like
HTML <template> elements with native cloning.
▸ Expressive - lit-html gives you the full power of JavaScript and functional programming
patterns.
▸ Extensible - Different dialects of templates can be created with additional features for setting
element properties, declarative event handlers and more.
▸ It can be used standalone for simple tasks, or combined with a framework or component model,
like Web Components, for a full-featured UI development platform.
▸ It has an awesome VSC extension for syntax highlighting and formatting.
TAG FUNCTIONS
WEB COMPONENTS EVERYWHERE
TAG FUNCTIONS
function myTagFn(str, ...expr) {
console.log(str, expr);
return str.reduce((acc, curr, i) => acc + curr + (expr[i] || ''), '');
}
myTagFn`1+1 equals ${1+1} and 3 + 3 equals ${3+3} ${3+2}`
> (4) ["1+1 equals ", " and 3 + 3 equals ", " ", ""] (3) [2, 6, 5]
> “1+1 equals 2 and 3 + 3 equals 6 5"
Console
WEB COMPONENTS EVERYWHERE
RESOURCES
▸ LitHTML demo - https://github.com/Polymer/lit-html/blob/master/demo/
clock.js
WEB COMPONENTS EVERYWHERE
FRAMEWORKS
▸ StencilJS - a simple library for generating Web Components and
progressive web apps (PWA). 

(built by the Ionic Framework team for its next generation of performant mobile and desktop Web
Components)
▸ Polymer - library for creating web components.

(built by Google and used by YouTube, Netflix, Google Earth and others)
▸ SkateJS - library providing functional abstraction over web
components.
▸ Angular Elements
WEB COMPONENTS EVERYWHERE
WEB COMPONENTS SERVER SIDE RENDERING
▸ SkateJS SSR - @skatejs/ssr is a web component server-side
rendering and testing library. (uses undom)
▸ Rendertron - Rendertron is a headless Chrome rendering solution
designed to render & serialise web pages on the fly.
▸ Domino - Server-side DOM implementation based on Mozilla's
dom.js
ANGULAR ELEMENTS
WEB COMPONENTS EVERYWHERE
ANGULAR ELEMENTS
▸ A part of Angular Labs set.
▸ Angular elements are Angular components
packaged as Custom Elements.
WEB COMPONENTS EVERYWHERE
ANGULAR ELEMENTS
▸ Angular’s createCustomElement() function transforms an Angular component,
together with its dependencies, to a class that is congured to produce a self-
bootstrapping instance of the component.
▸ It transforms the property names to make them compatible with custom
elements.
▸ Component outputs are dispatched as HTML Custom Events, with the name
of the custom event matching the output name.
▸ Then customElements.define() is used to register our custom element.
Transformation
DEMOTHE ANGULAR WAY
WEB COMPONENTS EVERYWHERE
NEW ANGULAR PROJECT
ng new angular-elements // Create new Angular CLI project
cd angular-elements
ng add @angular/elements // Add angular elements package
ng g c counter // Generate a new component
// Navigate to our new project
WEB COMPONENTS EVERYWHERE
ANGULAR ELEMENTS The generated component
@Component({
selector: 'app-counter',
templateUrl: './counter.component.html',
styleUrls: ['./counter.component.css'],
encapsulation: ViewEncapsulation.Native
})
export class CounterComponent {
@Input() counter = 0;
constructor() { }
inc() { this.counter++; }
dec() { this.counter--; }
}
src/app/counter/counter.component.ts
WEB COMPONENTS EVERYWHERE
ANGULAR ELEMENTS Add View Encapsulation via Shadow DOM (Native)
@Component({
selector: 'app-counter',
templateUrl: './counter.component.html',
styleUrls: ['./counter.component.css'],
encapsulation: ViewEncapsulation.Native
})
export class CounterComponent {
@Input() counter = 0;
constructor() { }
inc() { this.counter++; }
dec() { this.counter--; }
}
src/app/counter/counter.component.ts
WEB COMPONENTS EVERYWHERE
ANGULAR ELEMENTS Create a counter input property
@Component({
selector: 'app-counter',
templateUrl: './counter.component.html',
styleUrls: ['./counter.component.css'],
encapsulation: ViewEncapsulation.Native
})
export class CounterComponent {
@Input() counter = 0;
constructor() { }
inc() { this.counter++; }
dec() { this.counter--; }
}
src/app/counter/counter.component.ts
WEB COMPONENTS EVERYWHERE
ANGULAR ELEMENTS Create counter handlers
@Component({
selector: 'app-counter',
templateUrl: './counter.component.html',
styleUrls: ['./counter.component.css'],
encapsulation: ViewEncapsulation.Native
})
export class CounterComponent {
@Input() counter = 0;
constructor() { }
inc() { this.counter++; }
dec() { this.counter--; }
}
src/app/counter/counter.component.ts
WEB COMPONENTS EVERYWHERE
ANGULAR ELEMENTS Present the counter value
<div>{{counter}}</div>
<button (click)="dec()">Dec</button>
<button (click)="inc()">Inc</button>
src/app/counter/counter.component.html
WEB COMPONENTS EVERYWHERE
ANGULAR ELEMENTS Create the manipulation buttons and connect the to the handlers
<div>{{counter}}</div>
<button (click)="dec()">Dec</button>
<button (click)="inc()">Inc</button>
src/app/counter/counter.component.html
THATS IT?
NOT EXACTLY…
WEB COMPONENTS EVERYWHERE
NEW ANGULAR MODULE
ng g m counter // Create new counter module
WEB COMPONENTS EVERYWHERE
ANGULAR ELEMENTS Create a module for out custom elements
@NgModule({
imports: [
BrowserModule
],
declarations: [],
entryComponents: [CounterComponent]
})
export class CounterModule {
constructor(private injector: Injector) {}
ngDoBootstrap() {
const el = createCustomElement(CounterComponent, { injector: this.injector });
customElements.define('app-counter', el);
}
}
src/app/counter/counter.module.ts
WEB COMPONENTS EVERYWHERE
ANGULAR ELEMENTS Create a module for out custom elements
@NgModule({
imports: [
BrowserModule
],
declarations: [CounterComponent],
entryComponents: [CounterComponent]
})
export class CounterModule {
constructor(private injector: Injector) {}
ngDoBootstrap() {
const el = createCustomElement(CounterComponent, { injector: this.injector });
customElements.define('app-counter', el);
}
}
src/app/counter/counter.module.ts
WEB COMPONENTS EVERYWHERE
ANGULAR ELEMENTS Create a module for out custom elements
@NgModule({
imports: [
BrowserModule
],
declarations: [CounterComponent],
entryComponents: [CounterComponent]
})
export class CounterModule {
constructor(private injector: Injector) {}
ngDoBootstrap() {
const el = createCustomElement(CounterComponent, { injector: this.injector });
customElements.define('app-counter', el);
}
}
src/app/counter/counter.module.ts
WEB COMPONENTS EVERYWHERE
ANGULAR ELEMENTS Create a module for out custom elements
@NgModule({
imports: [
BrowserModule
],
declarations: [CounterComponent],
entryComponents: [CounterComponent]
})
export class CounterModule {
constructor(private injector: Injector) {}
ngDoBootstrap() {
const el = createCustomElement(CounterComponent, { injector: this.injector });
customElements.define('app-counter', el);
}
}
src/app/counter/counter.module.ts
WEB COMPONENTS EVERYWHERE
ANGULAR ELEMENTS Create a module for out custom elements
@NgModule({
imports: [
BrowserModule
],
declarations: [CounterComponent],
entryComponents: [CounterComponent]
})
export class CounterModule {
constructor(private injector: Injector) {}
ngDoBootstrap() {
const el = createCustomElement(CounterComponent, { injector: this.injector });
customElements.define('app-counter', el);
}
}
src/app/counter/counter.module.ts
WEB COMPONENTS EVERYWHERE
ANGULAR ELEMENTS Create a module for out custom elements
@NgModule({
imports: [
BrowserModule
],
declarations: [CounterComponent],
entryComponents: [CounterComponent]
})
export class CounterModule {
constructor(private injector: Injector) {}
ngDoBootstrap() {
const el = createCustomElement(CounterComponent, { injector: this.injector });
customElements.define('app-counter', el);
}
}
src/app/counter/counter.module.ts
WEB COMPONENTS EVERYWHERE
ANGULAR ELEMENTS Create a module for out custom elements
@NgModule({
imports: [
BrowserModule
],
declarations: [CounterComponent],
entryComponents: [CounterComponent]
})
export class CounterModule {
constructor(private injector: Injector) {}
ngDoBootstrap() {
const el = createCustomElement(CounterComponent, { injector: this.injector });
customElements.define('app-counter', el);
}
}
src/app/counter/counter.module.ts
😵
WEB COMPONENTS EVERYWHERE
IVY - THE NEW RENDERING ENGINE FOR ANGULAR
▸ Incremental builds and uses monomorphic data structures internally (Fast)
▸ Tree Shaking (Efficient)
https://github.com/angular/angular/blob/master/packages/compiler/design/architecture.md
WEB COMPONENTS EVERYWHERE
ANGULAR ELEMENTS Using the Ivy hopefully we will have something like:
@Component({
selector: 'app-counter',
templateUrl: './counter.component.html',
styleUrls: ['./counter.component.css'],
customElement: true
})
export class CounterComponent {
@Input() counter = 0;
constructor() { }
inc() { this.counter++; }
dec() { this.counter--; }
}
src/app/counter/counter.component.ts
WEB COMPONENTS EVERYWHERE
FAQ
▸ Can we use Dependency Injection?
▸ What about Content Projection?
▸ Can we still use Slots?
WEB COMPONENTS EVERYWHERE
BENEFITS OF USING ANGULAR ELEMENTS
▸ All components can be reused across JavaScript applications.
▸ Creating Dynamic Components.
▸ Hybrid Rendering - Server Side Rendering with Custom Elements that don’t
wait for the application to bootstrap to start working.
▸ Micro Frontends Architecture - Vertical Application Scaling (Working with
multiple small applications instead of a big monolith.)
https://micro-frontends.org
WEB COMPONENTS EVERYWHERE
ADDITIONAL RESOURCES
▸ https://custom-elements-everywhere.com - This project runs a suite of tests
against each framework to identify interoperability issues, and highlight
potential xes already implemented in other frameworks.
WEB COMPONENTS EVERYWHERE
CONNECT
GitHub > https://github.com/iliaidakiev (/slides/ - list of future and past events)
Twitter > @ilia_idakiev
THANK YOU!

Weitere ähnliche Inhalte

Was ist angesagt?

Was ist angesagt? (20)

Advanced angular
Advanced angularAdvanced angular
Advanced angular
 
Web Components
Web ComponentsWeb Components
Web Components
 
Advanced Git
Advanced GitAdvanced Git
Advanced Git
 
Sightly - Part 2
Sightly - Part 2Sightly - Part 2
Sightly - Part 2
 
Bootstrap Components Quick Overview
Bootstrap Components Quick OverviewBootstrap Components Quick Overview
Bootstrap Components Quick Overview
 
Flexbox
FlexboxFlexbox
Flexbox
 
React js
React jsReact js
React js
 
Builder pattern
Builder patternBuilder pattern
Builder pattern
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
An introduction to Vue.js
An introduction to Vue.jsAn introduction to Vue.js
An introduction to Vue.js
 
톰캣 운영 노하우
톰캣 운영 노하우톰캣 운영 노하우
톰캣 운영 노하우
 
Clean Architecture
Clean ArchitectureClean Architecture
Clean Architecture
 
React Architecture & Best Practices.pptx
React Architecture & Best Practices.pptxReact Architecture & Best Practices.pptx
React Architecture & Best Practices.pptx
 
Javascript best practices
Javascript best practicesJavascript best practices
Javascript best practices
 
HTML & CSS.ppt
HTML & CSS.pptHTML & CSS.ppt
HTML & CSS.ppt
 
Git & Github for beginners
Git & Github for beginnersGit & Github for beginners
Git & Github for beginners
 
Building Web Apps with WebAssembly and Blazor
Building Web Apps with WebAssembly and BlazorBuilding Web Apps with WebAssembly and Blazor
Building Web Apps with WebAssembly and Blazor
 
스프링 시큐리티 구조 이해
스프링 시큐리티 구조 이해스프링 시큐리티 구조 이해
스프링 시큐리티 구조 이해
 
What Is Virtual DOM In React JS.pptx
What Is Virtual DOM In React JS.pptxWhat Is Virtual DOM In React JS.pptx
What Is Virtual DOM In React JS.pptx
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
 

Ähnlich wie Web Components Everywhere

Practical AngularJS
Practical AngularJSPractical AngularJS
Practical AngularJS
Wei Ru
 
Knockout.js
Knockout.jsKnockout.js
Knockout.js
Vivek Rajan
 
Overview of The Scala Based Lift Web Framework
Overview of The Scala Based Lift Web FrameworkOverview of The Scala Based Lift Web Framework
Overview of The Scala Based Lift Web Framework
IndicThreads
 
Scala based Lift Framework
Scala based Lift FrameworkScala based Lift Framework
Scala based Lift Framework
vhazrati
 
TurboGears2 Pluggable Applications
TurboGears2 Pluggable ApplicationsTurboGears2 Pluggable Applications
TurboGears2 Pluggable Applications
Alessandro Molina
 

Ähnlich wie Web Components Everywhere (20)

Creating lightweight JS Apps w/ Web Components and lit-html
Creating lightweight JS Apps w/ Web Components and lit-htmlCreating lightweight JS Apps w/ Web Components and lit-html
Creating lightweight JS Apps w/ Web Components and lit-html
 
Building Reusable Custom Elements With Angular
Building Reusable Custom Elements With AngularBuilding Reusable Custom Elements With Angular
Building Reusable Custom Elements With Angular
 
Backbone.js
Backbone.jsBackbone.js
Backbone.js
 
Magic of web components
Magic of web componentsMagic of web components
Magic of web components
 
Knockoutjs databinding
Knockoutjs databindingKnockoutjs databinding
Knockoutjs databinding
 
Practical AngularJS
Practical AngularJSPractical AngularJS
Practical AngularJS
 
Knockout.js
Knockout.jsKnockout.js
Knockout.js
 
An introduction to React.js
An introduction to React.jsAn introduction to React.js
An introduction to React.js
 
Overview Of Lift Framework
Overview Of Lift FrameworkOverview Of Lift Framework
Overview Of Lift Framework
 
Overview of The Scala Based Lift Web Framework
Overview of The Scala Based Lift Web FrameworkOverview of The Scala Based Lift Web Framework
Overview of The Scala Based Lift Web Framework
 
Scala based Lift Framework
Scala based Lift FrameworkScala based Lift Framework
Scala based Lift Framework
 
Jquery presentation
Jquery presentationJquery presentation
Jquery presentation
 
Will your code blend? : Toronto Code Camp 2010 : Barry Gervin
Will your code blend? : Toronto Code Camp 2010 : Barry GervinWill your code blend? : Toronto Code Camp 2010 : Barry Gervin
Will your code blend? : Toronto Code Camp 2010 : Barry Gervin
 
Choosing a Javascript Framework
Choosing a Javascript FrameworkChoosing a Javascript Framework
Choosing a Javascript Framework
 
Web Components v1
Web Components v1Web Components v1
Web Components v1
 
Backbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVCBackbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVC
 
J query b_dotnet_ug_meet_12_may_2012
J query b_dotnet_ug_meet_12_may_2012J query b_dotnet_ug_meet_12_may_2012
J query b_dotnet_ug_meet_12_may_2012
 
Reactive Type-safe WebComponents
Reactive Type-safe WebComponentsReactive Type-safe WebComponents
Reactive Type-safe WebComponents
 
Introduction to angular js
Introduction to angular jsIntroduction to angular js
Introduction to angular js
 
TurboGears2 Pluggable Applications
TurboGears2 Pluggable ApplicationsTurboGears2 Pluggable Applications
TurboGears2 Pluggable Applications
 

Mehr von Ilia Idakiev

Mehr von Ilia Idakiev (17)

No more promises lets RxJS 2 Edit
No more promises lets RxJS 2 EditNo more promises lets RxJS 2 Edit
No more promises lets RxJS 2 Edit
 
Enterprise State Management with NGRX/platform
Enterprise State Management with NGRX/platformEnterprise State Management with NGRX/platform
Enterprise State Management with NGRX/platform
 
Deep Dive into Zone.JS
Deep Dive into Zone.JSDeep Dive into Zone.JS
Deep Dive into Zone.JS
 
RxJS Schedulers - Controlling Time
RxJS Schedulers - Controlling TimeRxJS Schedulers - Controlling Time
RxJS Schedulers - Controlling Time
 
No More Promises! Let's RxJS!
No More Promises! Let's RxJS!No More Promises! Let's RxJS!
No More Promises! Let's RxJS!
 
Marble Testing RxJS streams
Marble Testing RxJS streamsMarble Testing RxJS streams
Marble Testing RxJS streams
 
Deterministic JavaScript Applications
Deterministic JavaScript ApplicationsDeterministic JavaScript Applications
Deterministic JavaScript Applications
 
State management for enterprise angular applications
State management for enterprise angular applicationsState management for enterprise angular applications
State management for enterprise angular applications
 
Offline progressive web apps with NodeJS and React
Offline progressive web apps with NodeJS and ReactOffline progressive web apps with NodeJS and React
Offline progressive web apps with NodeJS and React
 
Testing rx js using marbles within angular
Testing rx js using marbles within angularTesting rx js using marbles within angular
Testing rx js using marbles within angular
 
Predictable reactive state management for enterprise apps using NGRX/platform
Predictable reactive state management for enterprise apps using NGRX/platformPredictable reactive state management for enterprise apps using NGRX/platform
Predictable reactive state management for enterprise apps using NGRX/platform
 
Angular server side rendering with NodeJS - In Pursuit Of Speed
Angular server side rendering with NodeJS - In Pursuit Of SpeedAngular server side rendering with NodeJS - In Pursuit Of Speed
Angular server side rendering with NodeJS - In Pursuit Of Speed
 
Angular Offline Progressive Web Apps With NodeJS
Angular Offline Progressive Web Apps With NodeJSAngular Offline Progressive Web Apps With NodeJS
Angular Offline Progressive Web Apps With NodeJS
 
Introduction to Offline Progressive Web Applications
Introduction to Offline Progressive Web ApplicationsIntroduction to Offline Progressive Web Applications
Introduction to Offline Progressive Web Applications
 
Reflective injection using TypeScript
Reflective injection using TypeScriptReflective injection using TypeScript
Reflective injection using TypeScript
 
Zone.js
Zone.jsZone.js
Zone.js
 
Predictable reactive state management - ngrx
Predictable reactive state management - ngrxPredictable reactive state management - ngrx
Predictable reactive state management - ngrx
 

KĂźrzlich hochgeladen

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

KĂźrzlich hochgeladen (20)

GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 

Web Components Everywhere

  • 2. A B O U T M E { "name": "Ilia Idakiev", "experience": [ "Developer & Founder of HNS/HG", "Lecturer in Advanced JS @ Soa University", "Contractor / Consultant", "Public / Private Courses" ], "involvedIn": [ "Angular Soa", "SoaJS", "BeerJS", ] }
  • 3. WEB COMPONENTS EVERYWHERE SEPARATION OF CONCERNS (SOC) ▸ Design principle for separating a computer program into distinct sections, such that each section addresses a separate concern. (Modularity)
  • 4. WEB COMPONENTS EVERYWHERE S.O.L.I.D PRINCIPLES OF OBJECT-ORIENTED PROGRAMMING ▸ Single Responsibility Principle ▸ Open / Close Principle ▸ Liskov Substitution Principle ▸ Interface Segregation Principle ▸ Dependency Inversion Principle http://aspiringcraftsman.com/2011/12/08/solid-javascript-single-responsibility-principle/
  • 5. WEB COMPONENTS EVERYWHERE WEB COMPONENTS ▸ Introduced by Alex Russell (Chrome team @ Google) 
 at Fronteers Conference 2011 ▸ A set of features currently being added by the W3C to the HTML and DOM specications that allow the creation of reusable widgets or components in web documents and web applications. ▸ The intention behind them is to bring component-based software engineering to the World Wide Web.
  • 6. WEB COMPONENTS EVERYWHERE WEB COMPONENTS FEATURES: ▸ HTML Templates - an HTML fragment is not rendered, but stored until it is instantiated via JavaScript. ▸ Shadow DOM - Encapsulated DOM and styling, with composition. ▸ Custom Elements - APIs to dene new HTML elements. ▸ HTML Imports - Declarative methods of importing HTML documents into other documents. (Replaced by ES6 Imports).
  • 8. WEB COMPONENTS EVERYWHERE DEFINE CUSTOM ELEMENT (function () { const template = createTemplate('<div>Hello World<div>'); class Counter extends HTMLElement { constructor() { super(); const shadowRoot = this.attachShadow({ mode: 'open' }); shadowRoot.appendChild(template.content.cloneNode(true)); } } customElements.define('hg-counter', Counter); }()); Create an isolated scope counter.js
  • 9. WEB COMPONENTS EVERYWHERE (function () { const template = createTemplate('<div>Hello World<div>'); class Counter extends HTMLElement { constructor() { super(); const shadowRoot = this.attachShadow({ mode: 'open' }); shadowRoot.appendChild(template.content.cloneNode(true)); } } customElements.define('hg-counter', Counter); }()); DEFINE CUSTOM ELEMENT Create a new class that extends HTMLElement counter.js
  • 10. WEB COMPONENTS EVERYWHERE (function () { const template = createTemplate('<div>Hello World<div>'); class Counter extends HTMLElement { constructor() { super(); const shadowRoot = this.attachShadow({ mode: 'open' }); shadowRoot.appendChild(template.content.cloneNode(true)); } } customElements.define('hg-counter', Counter); }()); DEFINE CUSTOM ELEMENT Register the new custom element. counter.js
  • 11. WEB COMPONENTS EVERYWHERE HTML TEMPLATES ▸ The <template> tag holds its content hidden from the client. ▸ Content inside a <template> tag will be parsed but not rendered. ▸ The content can be visible and rendered later by using JavaScript.
  • 12. WEB COMPONENTS EVERYWHERE WAYS TO CREATE A TEMPLATE <template id="template"> <h2>Hello World</h2> </template> const template = document.createElement('template'); template.innerHTML = '<h2>Hello World</h2>'; Using HTML Using JavaScript
  • 13. WEB COMPONENTS EVERYWHERE CREATE TEMPLATE HELPER FUNCTION function createTemplate(string) { const template = document.createElement('template'); template.innerHTML = string; return template; } utils.js
  • 14. WEB COMPONENTS EVERYWHERE CREATE THE TEMPLATE (function () { const template = createTemplate('<div>Hello World<div>'); class Counter extends HTMLElement { constructor() { super(); const shadowRoot = this.attachShadow({ mode: 'open' }); shadowRoot.appendChild(template.content.cloneNode(true)); } } customElements.define('hg-counter', Counter); }()); Use the create template helper function. counter.js
  • 15. WEB COMPONENTS EVERYWHERE SHADOW DOM ▸ Isolated DOM - The component's DOM is self-contained (e.g. document.querySelector() won't return nodes in the component's shadow DOM). ▸ Scoped CSS - CSS dened inside shadow DOM is scoped to it. Style rules don't leak out and page styles don't bleed in. ▸ Composition - done with the <slot> element.
 (Slots are placeholders inside your component that users can ll with their own markup).
  • 16. WEB COMPONENTS EVERYWHERE DEFINE CUSTOM ELEMENT (function () { const template = createTemplate('<div>Hello World<div>'); class Counter extends HTMLElement { constructor() { super(); const shadowRoot = this.attachShadow({ mode: 'open' }); shadowRoot.appendChild(template.content.cloneNode(true)); } } customElements.define('hg-counter', Counter); }()); counter.js Utilise the class constructor.
  • 17. WEB COMPONENTS EVERYWHERE ATTACH SHADOW DOM (function () { const template = createTemplate('<div>Hello World<div>'); class Counter extends HTMLElement { constructor() { super(); const shadowRoot = this.attachShadow({ mode: 'open' }); shadowRoot.appendChild(template.content.cloneNode(true)); } } customElements.define('hg-counter', Counter); }()); Attach the shadow DOM. counter.js
  • 18. WEB COMPONENTS EVERYWHERE (function () { const template = createTemplate('<div>Hello World<div>'); class Counter extends HTMLElement { constructor() { super(); const shadowRoot = this.attachShadow({ mode: 'open' }); shadowRoot.appendChild(template.content.cloneNode(true)); } } customElements.define('hg-counter', Counter); }()); CREATE THE TEMPLATE Attach the template contents to the shadow root. counter.js
  • 19. WEB COMPONENTS EVERYWHERE USE OUR CUSTOM ELEMENT <body> <hg-counter></hg-counter> <script src="./util.js"></script> <script src="./counter.js"></script> </body> index.html
  • 20. WEB COMPONENTS EVERYWHERE EXTEND OUR CUSTOM ELEMENT index.html (function () { const template = createTemplate(` <div name="value"></div> <button data-type=“dec">-</button> <button data-type="inc">+</button> `); class Counter extends HTMLElement { constructor() { super();
  • 21. WEB COMPONENTS EVERYWHERE EXTEND OUR CUSTOM ELEMENT index.html constructor() { super(); const shadowRoot = this.attachShadow({ mode: 'open' }); shadowRoot.appendChild(template.content.cloneNode(true)); shadowRoot.addEventListener('click', ({ target }) => { const type = target.getAttribute('data-type'); if (type === 'dec') { this.counter--; } else if (type === 'inc') { this.counter++; } });
  • 22. WEB COMPONENTS EVERYWHERE UPDATING THE DOM utils.js function updateDOM(root, updates) { updates.forEach(item => { root.querySelectorAll(`[name=${item.name}]`).forEach(element => element.textContent = item.value ); }); }
  • 23. WEB COMPONENTS EVERYWHERE EXTEND OUR CUSTOM ELEMENT index.html class Counter extends HTMLElement { set counter(value) { this._counter = value; } get counter() { return this._counter; } constructor() { super(); const shadowRoot = this.attachShadow({ mode: 'open' }); shadowRoot.appendChild(template.content.cloneNode(true)); this.counter = 0;
  • 24. WEB COMPONENTS EVERYWHERE EXTEND OUR CUSTOM ELEMENT index.html class Counter extends HTMLElement { constructor() { super(); const shadowRoot = this.attachShadow({ mode: 'open' }); shadowRoot.appendChild(template.content.cloneNode(true)); this.counter = 0; this._update = () => { updateDOM(shadowRoot, [{ name: 'value', value: this.counter }]); }
  • 25. WEB COMPONENTS EVERYWHERE EXTEND OUR CUSTOM ELEMENT index.html class Counter extends HTMLElement { set counter(value) { this._counter = value; this._update(); } get counter() { return this._counter; } constructor() { super(); const shadowRoot = this.attachShadow({ mode: 'open' }); shadowRoot.appendChild(template.content.cloneNode(true)); this.counter = 0;
  • 26. WEB COMPONENTS EVERYWHERE CUSTOM COMPONENT ATTRIBUTES index.html <body> <hg-counter value="10"></hg-counter> <script src="./util.js"></script> <script src="./counter.js"></script> </body>
  • 27. WEB COMPONENTS EVERYWHERE CUSTOM ELEMENTS LIFECYCLE CALLBACKS ▸ connectedCallback - Invoked each time the custom element is appended into a document-connected element. This will happen each time the node is moved, and may happen before the element's contents have been fully parsed. ▸ disconnectedCallback - Invoked each time the custom element is disconnected from the document's DOM. ▸ attributeChangedCallback - Invoked each time one of the custom element's attributes is added, removed, or changed. ▸ adoptedCallback - Invoked each time the custom element is moved to a new document.
  • 28. WEB COMPONENTS EVERYWHERE CUSTOM COMPONENT ATTRIBUTES index.html class Counter extends HTMLElement { static get observedAttributes() { return ['value']; } attributeChangedCallback(name, oldValue, newValue) { if (name === 'value') { this.counter = newValue; } } constructor() { Handle attribute changes
  • 29. WEB COMPONENTS EVERYWHERE CUSTOM COMPONENT ATTRIBUTES index.html class Counter extends HTMLElement { static get observedAttributes() { return ['value']; } attributeChangedCallback(name, oldValue, newValue) { if (name === 'value') { this.counter = newValue; } } constructor() { Dene which attributes should be watched
  • 31. WEB COMPONENTS EVERYWHERE CUSTOM COMPONENT STYLES index.html Apply scoped styles to our component (function () { const template = createTemplate(` <style> :host { display: flex; } div[name="value"] { min-width: 30px; } </style> <div name="value"></div> <button data-type="dec">-</button> <button data-type="inc">+</button> `); class Counter extends HTMLElement {
  • 32. WEB COMPONENTS EVERYWHERE WEB COMPONENT CSS ▸ :host - selects the shadow host of the shadow DOM ▸ :host() - match only if the selector given as the function's parameter matches the shadow host. ▸ :host-context() -  match only if the selector given as the function's parameter matches the shadow host's ancestor(s) in the place it sits inside the DOM hierarchy. ▸ ::slotted() - represents any element that has been placed into a slot inside an HTML template
  • 34. WEB COMPONENTS EVERYWHERE CUSTOM EVENTS Dispatching custom event const test = shadowRoot.getElementById('element-button'); test.addEventListener('click', () => { this.dispatchEvent(new CustomEvent('toggle', { detail: { value: true } })) }); custom-element.js
  • 35. WEB COMPONENTS EVERYWHERE CUSTOM EVENTS Listening for custom event • CustomEvent {isTrusted: false, detail: {value: true}, type: "toggle", …} const el = document.getElementById('my-custom-element'); el.addEventListener('toggle', e => { console.log(e); }); main.js Console
  • 36. WEB COMPONENTS EVERYWHERE FURTHER READING ▸ Extending different HTML Elements
 (e.g. HTMLButton)
  • 37. WEB COMPONENTS EVERYWHERE BENEFITS OF USING CUSTOM COMPONENTS ▸ Framework agnostic - Written in JavaScript and native to the browser. ▸ Simplies CSS - Scoped DOM means you can use simple CSS selectors, more generic id/class names, and not worry about naming conflicts. • Productivity - Think of apps in chunks of DOM rather than one large (global) page. ▸ Productivity - Think of apps in chunks of DOM rather than one large (global) page.
  • 39. WEB COMPONENTS EVERYWHERE COSTS OF USING CUSTOM COMPONENTS ▸ Template Generation - manually construct the DOM for our templates 
 (No JSX features or Structural Directives) ▸ DOM Updates - manually track and handle changes to our DOM
 (No Virtual DOM or Change Detection)
  • 40. WEB COMPONENTS EVERYWHERE LIT HTML ▸ Library Developed by the Polymer Team @ GOOGLE ▸ Efcient - lit-html is extremely fast. It uses fast platform features like HTML <template> elements with native cloning. ▸ Expressive - lit-html gives you the full power of JavaScript and functional programming patterns. ▸ Extensible - Different dialects of templates can be created with additional features for setting element properties, declarative event handlers and more. ▸ It can be used standalone for simple tasks, or combined with a framework or component model, like Web Components, for a full-featured UI development platform. ▸ It has an awesome VSC extension for syntax highlighting and formatting.
  • 42. WEB COMPONENTS EVERYWHERE TAG FUNCTIONS function myTagFn(str, ...expr) { console.log(str, expr); return str.reduce((acc, curr, i) => acc + curr + (expr[i] || ''), ''); } myTagFn`1+1 equals ${1+1} and 3 + 3 equals ${3+3} ${3+2}` > (4) ["1+1 equals ", " and 3 + 3 equals ", " ", ""] (3) [2, 6, 5] > “1+1 equals 2 and 3 + 3 equals 6 5" Console
  • 43. WEB COMPONENTS EVERYWHERE RESOURCES ▸ LitHTML demo - https://github.com/Polymer/lit-html/blob/master/demo/ clock.js
  • 44. WEB COMPONENTS EVERYWHERE FRAMEWORKS ▸ StencilJS - a simple library for generating Web Components and progressive web apps (PWA). 
 (built by the Ionic Framework team for its next generation of performant mobile and desktop Web Components) ▸ Polymer - library for creating web components.
 (built by Google and used by YouTube, Netflix, Google Earth and others) ▸ SkateJS - library providing functional abstraction over web components. ▸ Angular Elements
  • 45. WEB COMPONENTS EVERYWHERE WEB COMPONENTS SERVER SIDE RENDERING ▸ SkateJS SSR - @skatejs/ssr is a web component server-side rendering and testing library. (uses undom) ▸ Rendertron - Rendertron is a headless Chrome rendering solution designed to render & serialise web pages on the fly. ▸ Domino - Server-side DOM implementation based on Mozilla's dom.js
  • 47. WEB COMPONENTS EVERYWHERE ANGULAR ELEMENTS ▸ A part of Angular Labs set. ▸ Angular elements are Angular components packaged as Custom Elements.
  • 48. WEB COMPONENTS EVERYWHERE ANGULAR ELEMENTS ▸ Angular’s createCustomElement() function transforms an Angular component, together with its dependencies, to a class that is congured to produce a self- bootstrapping instance of the component. ▸ It transforms the property names to make them compatible with custom elements. ▸ Component outputs are dispatched as HTML Custom Events, with the name of the custom event matching the output name. ▸ Then customElements.dene() is used to register our custom element. Transformation
  • 50. WEB COMPONENTS EVERYWHERE NEW ANGULAR PROJECT ng new angular-elements // Create new Angular CLI project cd angular-elements ng add @angular/elements // Add angular elements package ng g c counter // Generate a new component // Navigate to our new project
  • 51. WEB COMPONENTS EVERYWHERE ANGULAR ELEMENTS The generated component @Component({ selector: 'app-counter', templateUrl: './counter.component.html', styleUrls: ['./counter.component.css'], encapsulation: ViewEncapsulation.Native }) export class CounterComponent { @Input() counter = 0; constructor() { } inc() { this.counter++; } dec() { this.counter--; } } src/app/counter/counter.component.ts
  • 52. WEB COMPONENTS EVERYWHERE ANGULAR ELEMENTS Add View Encapsulation via Shadow DOM (Native) @Component({ selector: 'app-counter', templateUrl: './counter.component.html', styleUrls: ['./counter.component.css'], encapsulation: ViewEncapsulation.Native }) export class CounterComponent { @Input() counter = 0; constructor() { } inc() { this.counter++; } dec() { this.counter--; } } src/app/counter/counter.component.ts
  • 53. WEB COMPONENTS EVERYWHERE ANGULAR ELEMENTS Create a counter input property @Component({ selector: 'app-counter', templateUrl: './counter.component.html', styleUrls: ['./counter.component.css'], encapsulation: ViewEncapsulation.Native }) export class CounterComponent { @Input() counter = 0; constructor() { } inc() { this.counter++; } dec() { this.counter--; } } src/app/counter/counter.component.ts
  • 54. WEB COMPONENTS EVERYWHERE ANGULAR ELEMENTS Create counter handlers @Component({ selector: 'app-counter', templateUrl: './counter.component.html', styleUrls: ['./counter.component.css'], encapsulation: ViewEncapsulation.Native }) export class CounterComponent { @Input() counter = 0; constructor() { } inc() { this.counter++; } dec() { this.counter--; } } src/app/counter/counter.component.ts
  • 55. WEB COMPONENTS EVERYWHERE ANGULAR ELEMENTS Present the counter value <div>{{counter}}</div> <button (click)="dec()">Dec</button> <button (click)="inc()">Inc</button> src/app/counter/counter.component.html
  • 56. WEB COMPONENTS EVERYWHERE ANGULAR ELEMENTS Create the manipulation buttons and connect the to the handlers <div>{{counter}}</div> <button (click)="dec()">Dec</button> <button (click)="inc()">Inc</button> src/app/counter/counter.component.html
  • 59. WEB COMPONENTS EVERYWHERE NEW ANGULAR MODULE ng g m counter // Create new counter module
  • 60. WEB COMPONENTS EVERYWHERE ANGULAR ELEMENTS Create a module for out custom elements @NgModule({ imports: [ BrowserModule ], declarations: [], entryComponents: [CounterComponent] }) export class CounterModule { constructor(private injector: Injector) {} ngDoBootstrap() { const el = createCustomElement(CounterComponent, { injector: this.injector }); customElements.define('app-counter', el); } } src/app/counter/counter.module.ts
  • 61. WEB COMPONENTS EVERYWHERE ANGULAR ELEMENTS Create a module for out custom elements @NgModule({ imports: [ BrowserModule ], declarations: [CounterComponent], entryComponents: [CounterComponent] }) export class CounterModule { constructor(private injector: Injector) {} ngDoBootstrap() { const el = createCustomElement(CounterComponent, { injector: this.injector }); customElements.define('app-counter', el); } } src/app/counter/counter.module.ts
  • 62. WEB COMPONENTS EVERYWHERE ANGULAR ELEMENTS Create a module for out custom elements @NgModule({ imports: [ BrowserModule ], declarations: [CounterComponent], entryComponents: [CounterComponent] }) export class CounterModule { constructor(private injector: Injector) {} ngDoBootstrap() { const el = createCustomElement(CounterComponent, { injector: this.injector }); customElements.define('app-counter', el); } } src/app/counter/counter.module.ts
  • 63. WEB COMPONENTS EVERYWHERE ANGULAR ELEMENTS Create a module for out custom elements @NgModule({ imports: [ BrowserModule ], declarations: [CounterComponent], entryComponents: [CounterComponent] }) export class CounterModule { constructor(private injector: Injector) {} ngDoBootstrap() { const el = createCustomElement(CounterComponent, { injector: this.injector }); customElements.define('app-counter', el); } } src/app/counter/counter.module.ts
  • 64. WEB COMPONENTS EVERYWHERE ANGULAR ELEMENTS Create a module for out custom elements @NgModule({ imports: [ BrowserModule ], declarations: [CounterComponent], entryComponents: [CounterComponent] }) export class CounterModule { constructor(private injector: Injector) {} ngDoBootstrap() { const el = createCustomElement(CounterComponent, { injector: this.injector }); customElements.define('app-counter', el); } } src/app/counter/counter.module.ts
  • 65. WEB COMPONENTS EVERYWHERE ANGULAR ELEMENTS Create a module for out custom elements @NgModule({ imports: [ BrowserModule ], declarations: [CounterComponent], entryComponents: [CounterComponent] }) export class CounterModule { constructor(private injector: Injector) {} ngDoBootstrap() { const el = createCustomElement(CounterComponent, { injector: this.injector }); customElements.define('app-counter', el); } } src/app/counter/counter.module.ts
  • 66. WEB COMPONENTS EVERYWHERE ANGULAR ELEMENTS Create a module for out custom elements @NgModule({ imports: [ BrowserModule ], declarations: [CounterComponent], entryComponents: [CounterComponent] }) export class CounterModule { constructor(private injector: Injector) {} ngDoBootstrap() { const el = createCustomElement(CounterComponent, { injector: this.injector }); customElements.define('app-counter', el); } } src/app/counter/counter.module.ts
  • 68. WEB COMPONENTS EVERYWHERE IVY - THE NEW RENDERING ENGINE FOR ANGULAR ▸ Incremental builds and uses monomorphic data structures internally (Fast) ▸ Tree Shaking (Efcient) https://github.com/angular/angular/blob/master/packages/compiler/design/architecture.md
  • 69. WEB COMPONENTS EVERYWHERE ANGULAR ELEMENTS Using the Ivy hopefully we will have something like: @Component({ selector: 'app-counter', templateUrl: './counter.component.html', styleUrls: ['./counter.component.css'], customElement: true }) export class CounterComponent { @Input() counter = 0; constructor() { } inc() { this.counter++; } dec() { this.counter--; } } src/app/counter/counter.component.ts
  • 70. WEB COMPONENTS EVERYWHERE FAQ ▸ Can we use Dependency Injection? ▸ What about Content Projection? ▸ Can we still use Slots?
  • 71. WEB COMPONENTS EVERYWHERE BENEFITS OF USING ANGULAR ELEMENTS ▸ All components can be reused across JavaScript applications. ▸ Creating Dynamic Components. ▸ Hybrid Rendering - Server Side Rendering with Custom Elements that don’t wait for the application to bootstrap to start working. ▸ Micro Frontends Architecture - Vertical Application Scaling (Working with multiple small applications instead of a big monolith.) https://micro-frontends.org
  • 72. WEB COMPONENTS EVERYWHERE ADDITIONAL RESOURCES ▸ https://custom-elements-everywhere.com - This project runs a suite of tests against each framework to identify interoperability issues, and highlight potential xes already implemented in other frameworks.
  • 73. WEB COMPONENTS EVERYWHERE CONNECT GitHub > https://github.com/iliaidakiev (/slides/ - list of future and past events) Twitter > @ilia_idakiev