Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Web Components mit Angular: UI-Feuerwerk mit Struktur

Web Components mit Angular: UI-Feuerwerk mit Struktur

Was haben Bootstrap, Foundation oder Material Design gemeinsam? Richtig, sie bieten ein Framework, um unsere HTML5-Anwendung “entwicklerhübsch” darzustellen. Werden auf dieser Basis UI-Komponenten entwickelt, sind sie meist stark mit dem Konzept und Design des Frameworks verwoben. Eigene, oftmals durch Corporate Identity vorgegebene UI-Semantiken, Bedienkonzepte und Designkonzepte lassen sich nur schwer mit einem bestehenden Framework verheiraten. Die Portier- und Wiederverwendbarkeit leidet darunter. Doch moderne Konzepte, wie Web Components, Shadow DOM und Custom-HTML-Elemente können helfen, eigene, wiederverwendbare und gutaussehende UI-Komponenten zu entwickeln.

In dieser Session wollen Jörg Neumann und Manuel Rauber ein Konzept zur Entwicklung von Web Components mit dem Angular-Komponentenmodell vorstellen und zeigen mit welchem Workflow man vom Design bis hin zur stylisch umgesetzten App kommt.

GitHub: https://github.com/thinktecture/angulardays-2017-web-components

Manuel Rauber

October 11, 2017
Tweet

More Decks by Manuel Rauber

Other Decks in Programming

Transcript

  1. JÖRG NEUMANN | ACANDO GMBH MANUEL RAUBER | THINKTECTURE AG

    WEB COMPONENTS MIT ANGULAR UI-FEUERWERK MIT STRUKTUR
  2. JÖRG NEUMANN THEMEN § Mobile Development § UI-Technologien § Consulting,

    Coaching, Training KONTAKT § Mail: [email protected] § Twitter: @JoergNeumann § GitHub: https://github.com/JoergNeumann § Blog: www.HeadWriteLine.BlogSpot.com
  3. MANUEL RAUBER THEMEN § Cross-Plattform Entwicklung mit Angular § Backend

    Entwicklung mit Node.js, .NET oder .NET Core § Consultant, Speaker, Writer KONTAKT § Mail: [email protected] § Twitter: @manuelrauber § Blog: https://manuel-rauber.com
  4. <html> <head> <script src="fancyFramework.js"></script> </head> <body> <div id="fancyWidget"></div> </body> </html>

    § Keine Semantik § Intransparenz § Anpassungen schwierig § Framework-Abhängigkeit
  5. <html> <head> <script src="fancyFramework.js"></script> </head> <body> <div id="fancyWidget"> <span id="label"></span>

    <button id="incButton">+</button> <button id="decButton">-</button> … </div> </body> </html> § Global Scoping § Namenskonflikte § Styling-Konflikte
  6. <html> <head> <link rel="import" href="number-pad.html"></link> </head> <body> <number-pad value="1" minimum="1"

    maximum="1"> </number-pad> </body> </html> § Semantik § Local Scoping § Konfiguration § Bundle Import
  7. CUSTOM ELEMENTS Eine API zur Registrierung von eigenen HTML Elementen

    HTML TEMPLATES UI-Vorlage für eine Komponente SHADOW DOM Kapselung der inneren DOM- Bestandteile eines Elements HTML IMPORTS / ES MODULES Importieren von Komponenten WEB COMPONENTS
  8. <html> <head> <link rel="import" href="number-pad.html"></link> </head> <body> <number-pad value="1" minimum="1"

    maximum="1"> </number-pad> </body> </html> Custom Elements HTML Imports Shaddow DOM HTML Templates
  9. CUSTOM ELEMENTS DEFINITION § Eigene HTML-Elemente erstellen § Das Verhalten

    ist vom Dokument entkoppelt § Eigenständiges Lifecycle-Modell (Erstellung, Attributänderungen, …) <my-person firstName="Jörg"></my-person>
  10. CUSTOM ELEMENTS ENTWICKLUNG § Definition erfolgt in Form von ES6-Klassen

    § Ableitung von HTMLElement oder vorhandenem Element möglich § Custom Element muss im Browser registriert werden class MyPerson extends HTMLElement { constructor(){ super(); this._firstName = null; } get firstName(){ return this._firstName; } set firstName(newName){ this._firstName = newName; } } customElements.define("my-person", MyPerson);
  11. class MyElement extends HTMLElement { constructor() { super(); } connectedCallback()

    { // render … } disconnectedCallback() { // release … } attributeChangedCallback(attr, oldValue, newValue) { // refresh … } static get observedAttributes() { return ['myProperty']; } adoptedCallback(oldDocument, newDocument) { // change … } } customElements.define('my-element', MyElement); }); Element wird erstellt Element wurde in ein neues Dokument verschoben Element wurde aus Dokument entfernt Attribut wurde geändert Attribute für Verfolgung registrieren Element registrieren Element wurde ins Dokument eingefügt CUSTOM ELEMENTS – LIFECYCLE METHODS
  12. OBSERVED ATTRIBUTES DEFINITION § Attribute für automatische Änderungsverfolgung registrieren §

    Static Getter: observedAttributes § Benachrichtigung erfolgt über attributeChangedCallback class HelloElement extends HTMLElement { // 'name'-Attribute für Verfolgung registrieren static get observedAttributes() { return ['name']; } // Auf Änderung reagieren attributeChangedCallback(attr, oldValue, newValue) { if (attr == 'name') { this.textContent = 'Hallo ${newValue}!'; } } }
  13. HTML TEMPLATES DEFINITION § HTML Element <template> § Enthält Content

    der nach dem Laden nicht direkt gerendert wird § Wird erst bei Verwendung gerendert § Das Fragment kann im Dokument wiederverwendet werden <table id="producttable"> <thead> <tr> <td>Nr.</td> <td>Name</td> </tr> </thead> <tbody> <!-- wird dynamisch mit inhalt gefüllt --> </tbody> </table> <template id="productrow"> <tr> <td class="record"></td> <td></td> </tr> </template>
  14. <button onclick="useIt()">Use me</button> <div id="container"></div> <script> function useIt() { var

    content = document.querySelector('template').content; // Update something in the template DOM. var span = content.querySelector('span'); span.textContent = parseInt(span.textContent) + 1; document.querySelector('#container').appendChild( document.importNode(content, true)); } </script> <template> <div>Template used: <span>0</span></div> <script>alert('Thanks!')</script> </template> BEISPIEL
  15. SHADOW DOM DEFINITION § Bietet ein gekapseltes DOM / CSS

    für eine Komponente FEATURES § Isolated DOM: Lokale Elemente der Komponente sind von außen nicht sichtbar. § Scoped CSS: Lokale CSS-Definitionen wirken sich nur auf die Komponente aus. § Composition: Komponente kann von außen per Markup erweitert werden. § Einfaches CSS: Keine Konflikte mit id/class-Namen von außen. § Produktivität: App besteht aus gekapselten, wiederverwendbaren Komponenten.
  16. SHADOW DOM FUNKTIONSWEISE § Shadow DOM wird an existierendes Element

    angehängt § Kann statisches oder dynamisch erzeugtes Element sein § Kann natives oder benutzerdefiniertes Elemente sein § Aktivierung über Element.attachShadow() <html> <head></head> <body> <p id="host"></p> <script> var shadow = document.querySelector('#host') .attachShadow({mode: 'open'}); shadow.innerHTML = '<span>Some text</span>'; </script> </body> </html>
  17. SHADOW DOM - STYLING FUNKTIONSWEISE § Über <style> Element im

    Shadow DOM § Alles Styles sind lokal var shadow = document.querySelector('#host') .attachShadow({mode: 'open'}); shadow.innerHTML = '<span>Some new text</span>' + '<style>span { color: red; }</style>';
  18. SHADOW DOM - STYLING CSS SELECTORS § Pseudo-classes: :host, :host(),

    :host-context() § Pseudo-elements: ::slotted() § Combinator: >>> * <template id="template"> <style> :host { display: block; width: fit-content; font-size: 30px; background: #78909c; margin: 1px; padding: 14px; } span { background: white; font-size: 30px; } </style> <span id="counter"></span> </template> Document Element (Shadow Host) Shadow Root Content
  19. <div id="frame"> <span> <span id="label"></span> <slot name="addition"></slot> </span> <button id="increment-button">+</button>

    <button id="decrement-button">-</button> </div> <number-pad value="3" minimum="1" maximum="5"> <span slot="addition">kg</span> </number-pad> Verwendung: Template: SHADOW DOM - COMPOSITION DEFINITION § Ermöglicht das Einbetten von benutzerdefinierten Elementen § <slot>-Element im Template dient als Platzhalter § slot-Eigenschaft im Host stellt die Verbindung her
  20. HTML IMPORTS DEFINITION § Dienen zum Paketieren von Komponenten §

    Kann CSS und JavaScript enthalten § Einbindung erfolgt über: <link rel="import"> § Wird zukünftig von ES6-Modulen abgelöst <html> <head> <title>Human Being</title> <link rel="import" href="/imports/heart.html"> </head> <body> <p>What is a body without a heart?</p> </body> </html> var link = document.querySelector('link[rel=import]'); var heart = link.import; // Access DOM of the document in /imports/heart.html var pulse = heart.querySelector('div.pulse');
  21. BROWSER-KOMPATIBILITÄT Chrome Firefox IE 11+/ Edge Opera Safari 9+ Chrome

    (Android) Safari (iOS 9+) Template Native Native Partial Native Native Native Native HTML Imports Native Polyfill Polyfill Native Polyfill Native Polyfill Custom Elements Native Polyfill Polyfill Native Partial Native Partial Shadow DOM Native Polyfill Polyfill Native Partial Native Partial
  22. WEB COMPONENT POLYFILLS FUNKTIONSWEISE § Rüstet partiell fehlende Features nach

    § Funktioniert in neueren Browsern § Asynchroner Ladevorgang <html> <head> <!-- Load polyfills --> <script src="…/webcomponentsjs/webcomponents-loader.js"> </script> <script> window.addEventListener('WebComponentsReady', function() { <!-- Web Component Definition --> class MyElement extends HTMLElement { … } }); </script> </head> <body> <my-element></my-element> </body> </html>
  23. POLYMER WEB COMPONENTS-FRAMEWORK VON GOOGLE § Version 1.0 wurde 2015

    veröffentlicht § Version 2 in 2017 FEATURES § Einfache Entwicklung von Custom Elements § Two-Way Data Binding § Computed Properties § Conditional & Repeat Templates § Gesture Events § Element Library
  24. ANGULAR SINGLE-PAGE APPLICATION FRAMEWORK VON GOOGLE § Version 1 wurde

    2010 veröffentlicht § Version 2 in 2016 als kompletter Rewrite („Application Platform“) § Folgt semantischer Versionierung (a lá Google Chrome) FEATURES § Hierarchisches Komponentenmodell § Datenbindung § Datenflusssteuerung via Input & Output § Routing § Dependency Injection
  25. KOMPONENTEN HIERARCHISCHES KOMPONENTENMODELL § Kapseln Logik und Anzeige § Anzeige

    besteht aus Struktur und Design Parent -> Child Application Hackathons Users Hackathon Hackathon [hackathons]=“someExp” [hackathon]=“someExp” Child-> Parent Application Hackathons Users Hackathon Hackathon (rate)=“onRate()” (rate)=“onRate()” via @Input() via @Output()
  26. KOMPONENTEN VIEW ENCAPSULATION § None: Keine Kapselung der View, Stile

    von Komponenten können sich überschreiben § Emulated: Kapselung des Stylings via Rewriting der CSS-Bezeichner § Native: Kapselung des Templates via Shadow DOM @Component({ selector: 'hackathon-form', templateUrl: 'hackathonForm.html‘, encapsulation: ViewEncapsulation.None }) @Component({ selector: 'hackathon-form', templateUrl: 'hackathonForm.html‘, encapsulation: ViewEncapsulation.Native })
  27. KOMPONENTEN SLOTS § Definieren von außen bestimmbaren dynamischen Inhalt §

    Anzeige besteht aus Struktur und Design § Einfache oder mehrfache Slot(selektion) möglich
  28. FAZIT Komponenten helfen! § Bessere Struktur der App § Klare

    Semantik § Fördert die Wartbarkeit Web Components unterstützen § Kapselung von Markup & Code § Bessere Wiederverwendung § Bisher noch nicht 100% Browser Support Angular § Unterstützt eine komponentenbasierte Architektur
  29. RESSOURCEN REPOSITORY § https://github.com/thinktecture/angulardays-2017-web-components WEBCOMPONENTS.ORG § http://webcomponents.org/ WEB COMPONENTS TUTORIALS

    § https://blogs.windows.com/msedgedev/2015/07/14/bringing-componentization-to-the-web-an-overview-of- web-components/#TSeSZK7qXciRX8oE.99 § https://component.kitchen/tutorial WEB COMPONENTS BROWSER SUPPORT § http://webcomponents.org SHADOW DOM § https://developer.mozilla.org/en-US/docs/Web/Web_Components/Shadow_DOM
  30. WEB COMPONENTS: BROWSER SUPPORT ÜBERBLICK ALLER FEATURES/BROWSERS § http://jonrimmer.github.io/are-we-componentized-yet/ CUSTOM

    ELEMENTS § http://caniuse.com/#search=Custom%20elements SHADOW DOM § http://caniuse.com/#search=shadow%20dom TEMPLATES § http://caniuse.com/#feat=template HTML IMPORTS § http://caniuse.com/#search=html%20imports
  31. SPECS CUSTOM ELEMENTS § http://w3c.github.io/webcomponents/spec/custom/ HTML IMPORTS § http://w3c.github.io/webcomponents/spec/imports/ TEMPLATES

    § https://html.spec.whatwg.org/multipage/scripting.html#the-template-element SHADOW DOM § http://w3c.github.io/webcomponents/spec/shadow/