SlideShare a Scribd company logo
BUILDING REUSABLE CUSTOM ELEMENTS
USING ANGULAR
A B O U T M E
{
"name": "Ilia Idakiev",
"experience": [
"Developer & Founder of HNS/HG“,
"Lecturer in 'Advanced JS' @ Sofia University”,
"Contractor / Consultant",
“Public / Private Courses“
],
"involvedIn": [
"SofiaJS", "BeerJS", "Angular Sofia"
]
}
BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR
I LOVE VINYL
BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR
SEPARATION OF CONCERNS (SOC)
▸ Design principle for separating a computer program into distinct sections, such
that each section addresses a separate concern. (Modularity)
BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR
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/
BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR
MODE - VIEW - CONTROLLER
▸ MODEL - the central component of the pattern. It
is the application's dynamic data structure,
independent of the user interface. It directly
manages the data, logic and rules of the
application.
▸ VIEW - any output representation of information.
▸ CONTROLLER - accepts input and converts it to
commands for the model.
BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR
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 specifications 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.
BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR
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
BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR
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
BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR
(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
BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR
(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
BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR
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.
BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR
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
BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR
CREATE TEMPLATE HELPER FUNCTION
function createTemplate(string) {
const template = document.createElement('template');
template.innerHTML = string;
return template;
}
utils.js
BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR
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
BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR
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 fill with their own markup).
BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR
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.
BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR
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
BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR
(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
BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR
USE OUR CUSTOM ELEMENT
<body>
<hg-counter></hg-counter>
<script src="./util.js"></script>
<script src="./counter.js"></script>
</body>
index.html
BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR
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();
BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR
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++;
}
});
BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR
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;
BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR
UPDATING THE DOM
utils.js
function updateDOM(root, updates) {
updates.forEach(item => {
root.querySelectorAll(`[name=${item.name}]`).forEach(element =>
element.textContent = item.value
);
});
}
BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR
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
}]);
}
BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR
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;
BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR
CUSTOM COMPONENT ATTRIBUTES
index.html
<body>
<hg-counter value="10"></hg-counter>
<script src="./util.js"></script>
<script src="./counter.js"></script>
</body>
BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR
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.
BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR
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
BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR
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() {
Define which attributes should be watched
WHAT ABOUT STYLES?
BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR
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 {
BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR
FURTHER READING
▸ Extending different HTML Elements

(e.g. HTMLButton)
▸ Dispatching Custom Events
BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR
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.
BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR
BROWSER SUPPORT
BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR
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)
BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR
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.
BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR
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
BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR
WEB COMPONENTS SERVER SIDE RENDERING
▸ Rendertron - Rendertron is a headless Chrome rendering solution
designed to render & serialise web pages on the fly.
▸ SkateJS SSR - @skatejs/ssr is a web component server-side
rendering and testing library.
ANGULAR ELEMENTS
BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR
ANGULAR ELEMENTS
▸ A part of Angular Labs set.
▸ Angular elements are Angular components
packaged as Custom Elements.
BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR
ANGULAR ELEMENTS
▸ Angular’s createCustomElement() function transforms an Angular component,
together with its dependencies, to a class that is configured 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
BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR
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
BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR
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
BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR
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
BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR
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
BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR
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
BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR
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
BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR
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…
BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR
NEW ANGULAR MODULE
ng g m counter // Create new counter module
BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR
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
BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR
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
BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR
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
BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR
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
BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR
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
BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR
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
BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR
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
😵
BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR
IVY - THE NEW RENDERING ENGINE FOR ANGULAR
▸ Monomorphic (Fast) - All internal data structures are monomorphic.
▸ Tree Shaking (Efficient) - removing unused pieces of code from our
applications.
https://github.com/angular/angular/blob/master/packages/compiler/design/architecture.md
BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR
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
BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR
FAQ
▸ Can we use Dependency Injection?
▸ What about Content Projection?
▸ Can we still use Slots?
BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR
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
BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR
ADDITIONAL RESOURCES
▸ https://custom-elements-everywhere.com - This project runs a suite of tests
against each framework to identify interoperability issues, and highlight
potential fixes already implemented in other frameworks.
BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR
CONNECT
GitHub > https://github.com/iliaidakiev (/slides/ - list of future and past events)
Twitter > @ilia_idakiev
THANK YOU!
Ad

Recommended

PDF
AngularJS Framework
Barcamp Saigon
 
PPTX
AngularJs
syam kumar kk
 
PPTX
Jquery Complete Presentation along with Javascript Basics
EPAM Systems
 
PPTX
Angularjs Basics
Anuradha Bandara
 
PPTX
Practical AngularJS
Wei Ru
 
PDF
Integrating Angular js & three.js
Josh Staples
 
PDF
Reactive Type-safe WebComponents
Martin Hochel
 
PPTX
Angular js
Behind D Walls
 
PPTX
jQuery
Vishwa Mohan
 
PDF
[FEConf Korea 2017]Angular 컴포넌트 대화법
Jeado Ko
 
PPTX
AngularJS
LearningTech
 
PDF
Solid angular
Nir Kaufman
 
PDF
Backbone Basics with Examples
Sergey Bolshchikov
 
PDF
Angular.js is super cool
Maksym Hopei
 
PPTX
JQuery
Jacob Nelson
 
PPT
J Query(04 12 2008) Foiaz
testingphase
 
PPTX
Intro to AngularJs
SolTech, Inc.
 
PDF
JavaScript para Graficos y Visualizacion de Datos - BogotaJS
philogb
 
PDF
AngularJS: an introduction
Luigi De Russis
 
PDF
OpenCms Days 2014 - User Generated Content in OpenCms 9.5
Alkacon Software GmbH & Co. KG
 
PDF
Practical Model View Programming (Roadshow Version)
Marius Bugge Monsen
 
PPTX
Open Source Ajax Solution @OSDC.tw 2009
Robbie Cheng
 
PDF
Introduction to jQuery
Nagaraju Sangam
 
PDF
I os 03
信嘉 陳
 
PPTX
The AngularJS way
Boyan Mihaylov
 
PPT
Jquery
adm_exoplatform
 
PPTX
jQuery from the very beginning
Anis Ahmad
 
PPTX
AngularJS in 60ish Minutes
Dan Wahlin
 
PDF
Web Components Everywhere
Ilia Idakiev
 
PDF
Creating lightweight JS Apps w/ Web Components and lit-html
Ilia Idakiev
 

More Related Content

What's hot (20)

PPTX
jQuery
Vishwa Mohan
 
PDF
[FEConf Korea 2017]Angular 컴포넌트 대화법
Jeado Ko
 
PPTX
AngularJS
LearningTech
 
PDF
Solid angular
Nir Kaufman
 
PDF
Backbone Basics with Examples
Sergey Bolshchikov
 
PDF
Angular.js is super cool
Maksym Hopei
 
PPTX
JQuery
Jacob Nelson
 
PPT
J Query(04 12 2008) Foiaz
testingphase
 
PPTX
Intro to AngularJs
SolTech, Inc.
 
PDF
JavaScript para Graficos y Visualizacion de Datos - BogotaJS
philogb
 
PDF
AngularJS: an introduction
Luigi De Russis
 
PDF
OpenCms Days 2014 - User Generated Content in OpenCms 9.5
Alkacon Software GmbH & Co. KG
 
PDF
Practical Model View Programming (Roadshow Version)
Marius Bugge Monsen
 
PPTX
Open Source Ajax Solution @OSDC.tw 2009
Robbie Cheng
 
PDF
Introduction to jQuery
Nagaraju Sangam
 
PDF
I os 03
信嘉 陳
 
PPTX
The AngularJS way
Boyan Mihaylov
 
PPT
Jquery
adm_exoplatform
 
PPTX
jQuery from the very beginning
Anis Ahmad
 
PPTX
AngularJS in 60ish Minutes
Dan Wahlin
 
jQuery
Vishwa Mohan
 
[FEConf Korea 2017]Angular 컴포넌트 대화법
Jeado Ko
 
AngularJS
LearningTech
 
Solid angular
Nir Kaufman
 
Backbone Basics with Examples
Sergey Bolshchikov
 
Angular.js is super cool
Maksym Hopei
 
JQuery
Jacob Nelson
 
J Query(04 12 2008) Foiaz
testingphase
 
Intro to AngularJs
SolTech, Inc.
 
JavaScript para Graficos y Visualizacion de Datos - BogotaJS
philogb
 
AngularJS: an introduction
Luigi De Russis
 
OpenCms Days 2014 - User Generated Content in OpenCms 9.5
Alkacon Software GmbH & Co. KG
 
Practical Model View Programming (Roadshow Version)
Marius Bugge Monsen
 
Open Source Ajax Solution @OSDC.tw 2009
Robbie Cheng
 
Introduction to jQuery
Nagaraju Sangam
 
I os 03
信嘉 陳
 
The AngularJS way
Boyan Mihaylov
 
jQuery from the very beginning
Anis Ahmad
 
AngularJS in 60ish Minutes
Dan Wahlin
 

Similar to Building Reusable Custom Elements With Angular (20)

PDF
Web Components Everywhere
Ilia Idakiev
 
PDF
Creating lightweight JS Apps w/ Web Components and lit-html
Ilia Idakiev
 
PPT
Backbone.js
Knoldus Inc.
 
PPTX
AngularJS Internal
Eyal Vardi
 
PPTX
AngularJS Architecture
Eyal Vardi
 
PPTX
Magic of web components
HYS Enterprise
 
PPTX
AngularJs Workshop SDP December 28th 2014
Ran Wahle
 
PPTX
Javascript first-class citizenery
toddbr
 
PDF
Backbone.js — Introduction to client-side JavaScript MVC
pootsbook
 
PPTX
Knockout.js
Vivek Rajan
 
PPTX
Angular
LearningTech
 
PPTX
Angular
LearningTech
 
PDF
Introduction to angular js
Marco Vito Moscaritolo
 
ODP
Javascript frameworks: Backbone.js
Soós Gábor
 
PDF
Web Components and Modular CSS
Andrew Rota
 
DOCX
! Modernizr v2.0.6 httpwww.modernizr.com Copyri.docx
MARRY7
 
PPTX
Writing HTML5 Web Apps using Backbone.js and GAE
Ron Reiter
 
PDF
Knockoutjs databinding
Boulos Dib
 
PPTX
Cloud Endpoints _Polymer_ Material design by Martin Görner
European Innovation Academy
 
PDF
Introduction to Polymer and Firebase - Simon Gauvin
Simon Gauvin
 
Web Components Everywhere
Ilia Idakiev
 
Creating lightweight JS Apps w/ Web Components and lit-html
Ilia Idakiev
 
Backbone.js
Knoldus Inc.
 
AngularJS Internal
Eyal Vardi
 
AngularJS Architecture
Eyal Vardi
 
Magic of web components
HYS Enterprise
 
AngularJs Workshop SDP December 28th 2014
Ran Wahle
 
Javascript first-class citizenery
toddbr
 
Backbone.js — Introduction to client-side JavaScript MVC
pootsbook
 
Knockout.js
Vivek Rajan
 
Angular
LearningTech
 
Angular
LearningTech
 
Introduction to angular js
Marco Vito Moscaritolo
 
Javascript frameworks: Backbone.js
Soós Gábor
 
Web Components and Modular CSS
Andrew Rota
 
! Modernizr v2.0.6 httpwww.modernizr.com Copyri.docx
MARRY7
 
Writing HTML5 Web Apps using Backbone.js and GAE
Ron Reiter
 
Knockoutjs databinding
Boulos Dib
 
Cloud Endpoints _Polymer_ Material design by Martin Görner
European Innovation Academy
 
Introduction to Polymer and Firebase - Simon Gauvin
Simon Gauvin
 
Ad

More from Ilia Idakiev (17)

PDF
No more promises lets RxJS 2 Edit
Ilia Idakiev
 
PDF
Enterprise State Management with NGRX/platform
Ilia Idakiev
 
PDF
Deep Dive into Zone.JS
Ilia Idakiev
 
PDF
RxJS Schedulers - Controlling Time
Ilia Idakiev
 
PDF
No More Promises! Let's RxJS!
Ilia Idakiev
 
PDF
Marble Testing RxJS streams
Ilia Idakiev
 
PDF
Deterministic JavaScript Applications
Ilia Idakiev
 
PDF
State management for enterprise angular applications
Ilia Idakiev
 
PDF
Offline progressive web apps with NodeJS and React
Ilia Idakiev
 
PDF
Testing rx js using marbles within angular
Ilia Idakiev
 
PDF
Predictable reactive state management for enterprise apps using NGRX/platform
Ilia Idakiev
 
PDF
Angular server side rendering with NodeJS - In Pursuit Of Speed
Ilia Idakiev
 
PDF
Angular Offline Progressive Web Apps With NodeJS
Ilia Idakiev
 
PDF
Introduction to Offline Progressive Web Applications
Ilia Idakiev
 
PDF
Reflective injection using TypeScript
Ilia Idakiev
 
PDF
Zone.js
Ilia Idakiev
 
PDF
Predictable reactive state management - ngrx
Ilia Idakiev
 
No more promises lets RxJS 2 Edit
Ilia Idakiev
 
Enterprise State Management with NGRX/platform
Ilia Idakiev
 
Deep Dive into Zone.JS
Ilia Idakiev
 
RxJS Schedulers - Controlling Time
Ilia Idakiev
 
No More Promises! Let's RxJS!
Ilia Idakiev
 
Marble Testing RxJS streams
Ilia Idakiev
 
Deterministic JavaScript Applications
Ilia Idakiev
 
State management for enterprise angular applications
Ilia Idakiev
 
Offline progressive web apps with NodeJS and React
Ilia Idakiev
 
Testing rx js using marbles within angular
Ilia Idakiev
 
Predictable reactive state management for enterprise apps using NGRX/platform
Ilia Idakiev
 
Angular server side rendering with NodeJS - In Pursuit Of Speed
Ilia Idakiev
 
Angular Offline Progressive Web Apps With NodeJS
Ilia Idakiev
 
Introduction to Offline Progressive Web Applications
Ilia Idakiev
 
Reflective injection using TypeScript
Ilia Idakiev
 
Zone.js
Ilia Idakiev
 
Predictable reactive state management - ngrx
Ilia Idakiev
 
Ad

Recently uploaded (20)

PPTX
HYBRIDIZATION OF ALKANES AND ALKENES ...
karishmaduhijod1
 
PDF
Why Every Growing Business Needs a Staff Augmentation Company IN USA.pdf
mary rojas
 
PDF
Humans vs AI Call Agents - Qcall.ai's Special Report
Udit Goenka
 
DOCX
Enable Your Cloud Journey With Microsoft Trusted Partner | IFI Tech
IFI Techsolutions
 
PDF
Which Hiring Management Tools Offer the Best ROI?
HireME
 
PPTX
Sap basis role in public cloud in s/4hana.pptx
htmlprogrammer987
 
PPTX
Advance Doctor Appointment Booking App With Online Payment
AxisTechnolabs
 
PDF
Sysinfo OST to PST Converter Infographic
SysInfo Tools
 
PDF
OpenChain Webinar - AboutCode - Practical Compliance in One Stack – Licensing...
Shane Coughlan
 
PDF
Y - Recursion The Hard Way GopherCon EU 2025
Eleanor McHugh
 
PDF
Simplify Task, Team, and Project Management with Orangescrum Work
Orangescrum
 
PDF
Canva Pro Crack Free Download 2025-FREE LATEST
grete1122g
 
PPTX
IDM Crack with Internet Download Manager 6.42 Build 41 [Latest 2025]
pcprocore
 
PDF
Azure AI Foundry: The AI app and agent factory
Maxim Salnikov
 
DOCX
Best AI-Powered Wearable Tech for Remote Health Monitoring in 2025
SEOLIFT - SEO Company London
 
DOCX
Zoho Creator Solution for EI by Elsner Technologies.docx
Elsner Technologies Pvt. Ltd.
 
PPTX
AI for PV: Development and Governance for a Regulated Industry
Biologit
 
PDF
University Campus Navigation for All - Peak of Data & AI
Safe Software
 
PDF
Why Edge Computing Matters in Mobile Application Tech.pdf
IMG Global Infotech
 
PPTX
IObit Driver Booster Pro 12 Crack Latest Version Download
pcprocore
 
HYBRIDIZATION OF ALKANES AND ALKENES ...
karishmaduhijod1
 
Why Every Growing Business Needs a Staff Augmentation Company IN USA.pdf
mary rojas
 
Humans vs AI Call Agents - Qcall.ai's Special Report
Udit Goenka
 
Enable Your Cloud Journey With Microsoft Trusted Partner | IFI Tech
IFI Techsolutions
 
Which Hiring Management Tools Offer the Best ROI?
HireME
 
Sap basis role in public cloud in s/4hana.pptx
htmlprogrammer987
 
Advance Doctor Appointment Booking App With Online Payment
AxisTechnolabs
 
Sysinfo OST to PST Converter Infographic
SysInfo Tools
 
OpenChain Webinar - AboutCode - Practical Compliance in One Stack – Licensing...
Shane Coughlan
 
Y - Recursion The Hard Way GopherCon EU 2025
Eleanor McHugh
 
Simplify Task, Team, and Project Management with Orangescrum Work
Orangescrum
 
Canva Pro Crack Free Download 2025-FREE LATEST
grete1122g
 
IDM Crack with Internet Download Manager 6.42 Build 41 [Latest 2025]
pcprocore
 
Azure AI Foundry: The AI app and agent factory
Maxim Salnikov
 
Best AI-Powered Wearable Tech for Remote Health Monitoring in 2025
SEOLIFT - SEO Company London
 
Zoho Creator Solution for EI by Elsner Technologies.docx
Elsner Technologies Pvt. Ltd.
 
AI for PV: Development and Governance for a Regulated Industry
Biologit
 
University Campus Navigation for All - Peak of Data & AI
Safe Software
 
Why Edge Computing Matters in Mobile Application Tech.pdf
IMG Global Infotech
 
IObit Driver Booster Pro 12 Crack Latest Version Download
pcprocore
 

Building Reusable Custom Elements With Angular

  • 1. BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR
  • 2. A B O U T M E { "name": "Ilia Idakiev", "experience": [ "Developer & Founder of HNS/HG“, "Lecturer in 'Advanced JS' @ Sofia University”, "Contractor / Consultant", “Public / Private Courses“ ], "involvedIn": [ "SofiaJS", "BeerJS", "Angular Sofia" ] }
  • 3. BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR I LOVE VINYL
  • 4. BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR SEPARATION OF CONCERNS (SOC) ▸ Design principle for separating a computer program into distinct sections, such that each section addresses a separate concern. (Modularity)
  • 5. BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR 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/
  • 6. BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR MODE - VIEW - CONTROLLER ▸ MODEL - the central component of the pattern. It is the application's dynamic data structure, independent of the user interface. It directly manages the data, logic and rules of the application. ▸ VIEW - any output representation of information. ▸ CONTROLLER - accepts input and converts it to commands for the model.
  • 7. BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR 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 specifications 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.
  • 8. BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR 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).
  • 10. BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR 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
  • 11. BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR (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
  • 12. BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR (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
  • 13. BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR 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.
  • 14. BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR 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
  • 15. BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR CREATE TEMPLATE HELPER FUNCTION function createTemplate(string) { const template = document.createElement('template'); template.innerHTML = string; return template; } utils.js
  • 16. BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR 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
  • 17. BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR 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 fill with their own markup).
  • 18. BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR 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.
  • 19. BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR 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
  • 20. BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR (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
  • 21. BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR USE OUR CUSTOM ELEMENT <body> <hg-counter></hg-counter> <script src="./util.js"></script> <script src="./counter.js"></script> </body> index.html
  • 22. BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR 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();
  • 23. BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR 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++; } });
  • 24. BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR 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;
  • 25. BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR UPDATING THE DOM utils.js function updateDOM(root, updates) { updates.forEach(item => { root.querySelectorAll(`[name=${item.name}]`).forEach(element => element.textContent = item.value ); }); }
  • 26. BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR 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 }]); }
  • 27. BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR 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;
  • 28. BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR CUSTOM COMPONENT ATTRIBUTES index.html <body> <hg-counter value="10"></hg-counter> <script src="./util.js"></script> <script src="./counter.js"></script> </body>
  • 29. BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR 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.
  • 30. BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR 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
  • 31. BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR 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() { Define which attributes should be watched
  • 33. BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR 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 {
  • 34. BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR FURTHER READING ▸ Extending different HTML Elements
 (e.g. HTMLButton) ▸ Dispatching Custom Events
  • 35. BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR 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.
  • 36. BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR BROWSER SUPPORT
  • 37. BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR 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)
  • 38. BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR 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.
  • 39. BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR 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
  • 40. BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR WEB COMPONENTS SERVER SIDE RENDERING ▸ Rendertron - Rendertron is a headless Chrome rendering solution designed to render & serialise web pages on the fly. ▸ SkateJS SSR - @skatejs/ssr is a web component server-side rendering and testing library.
  • 42. BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR ANGULAR ELEMENTS ▸ A part of Angular Labs set. ▸ Angular elements are Angular components packaged as Custom Elements.
  • 43. BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR ANGULAR ELEMENTS ▸ Angular’s createCustomElement() function transforms an Angular component, together with its dependencies, to a class that is configured 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
  • 45. BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR 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
  • 46. BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR 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
  • 47. BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR 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
  • 48. BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR 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
  • 49. BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR 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
  • 50. BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR 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
  • 51. BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR 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
  • 54. BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR NEW ANGULAR MODULE ng g m counter // Create new counter module
  • 55. BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR 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
  • 56. BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR 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
  • 57. BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR 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
  • 58. BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR 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
  • 59. BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR 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
  • 60. BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR 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
  • 61. BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR 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. 😵
  • 63. BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR IVY - THE NEW RENDERING ENGINE FOR ANGULAR ▸ Monomorphic (Fast) - All internal data structures are monomorphic. ▸ Tree Shaking (Efficient) - removing unused pieces of code from our applications. https://github.com/angular/angular/blob/master/packages/compiler/design/architecture.md
  • 64. BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR 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
  • 65. BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR FAQ ▸ Can we use Dependency Injection? ▸ What about Content Projection? ▸ Can we still use Slots?
  • 66. BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR 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
  • 67. BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR ADDITIONAL RESOURCES ▸ https://custom-elements-everywhere.com - This project runs a suite of tests against each framework to identify interoperability issues, and highlight potential fixes already implemented in other frameworks.
  • 68. BUILDING REUSABLE CUSTOM ELEMENTS USING ANGULAR CONNECT GitHub > https://github.com/iliaidakiev (/slides/ - list of future and past events) Twitter > @ilia_idakiev