$30 off During Our Annual Pro Sale. View Details »

Angular Components erobern die (Web-)Welt!

Angular Components erobern die (Web-)Welt!

Mit Angular Elements bauen wir wiederverwendbare Komponenten, welche in beliebigen JavaScript Apps eingesetzt werden können. Nach einer kurzen Einführung zur Funktionsweise von Komponenten in Angular lernen die Teilnehmer in dieser DevSession, wie verschiedene Komponenten untereinander kommunizieren können. Im letzten Teil der DevSession lernen wir Angular Elements kennen. Angular Elements sind Custom Elements, welche in beliebige Web-Applikationen integriert werden können. Damit können wir wiederverwendbare Angular-Komponenten und -Widgets schreiben, die in nicht-Angular-Apps (z.B. React, Vue, Sharepoint, etc.) eingebettet werden können.

Thomas Gassmann

October 12, 2020
Tweet

More Decks by Thomas Gassmann

Other Decks in Programming

Transcript

  1. www.thomasgassmann.net
    @gassmannT
    Angular Components erobern die (Web-)Welt!t
    Web Developer Conference 2020
    Thomas Gassmann

    View Slide

  2. Why a Workshop about Angular Components
    • Components are a core concept of Angular
    • There are plenty of ways how to communicate with Components
    • With some tricks, the code, testability and performance can be
    improved.

    View Slide

  3. Agenda
    • Introduction into Components
    • Dynamic component loading
    • Communicating with a Template
    • ViewChild and ViewChildren
    • Communicating through a service
    • Angular Elements.

    View Slide

  4. DevSession
    • Einführung: 09:00 – 10:00 Uhr
    • Pause 15’
    • Component Communication: 10:15 – 11:15 Uhr
    • Pause 15’
    • Angular Elements: 11:30 – 13:00 Uhr

    View Slide

  5. Thomas Gassmann
    Principal Consultant,
    Trainer, Speaker
    [email protected]
    thomasgassmann.net
    @gassmannT

    View Slide

  6. What we are building

    View Slide

  7. Introduction

    View Slide

  8. All Angular Apps are component-based
    Component
    Template (HTML)
    Class
    Metadata

    View Slide

  9. An Angular app is a tree of components
    Component
    Component
    Component Component
    Component

    View Slide

  10. View Slide

  11. View Slide

  12. Data Binding overview
    ▪ {{}} => Display the value of a property in the UI
    ▪ [] => Bind an element-property to a property of
    your class
    ▪ () => Bind an element-event to a method of your
    class
    ▪ [()] => Bind a property two-way
    that you don’t have to think whether it’s ([]) or [()],
    just use the “banana in a box”-mnemonic to get
    the syntax right

    View Slide

  13. Simple Rendering with Interpolation
    ▪ Use an expression in {{ }}
    for example {{1 + 1}} will write out 2
    ▪ use the pipe iterator to pass the expression to a Pipe
    you can write your own pipes or use existing pipes
    like uppercase

    View Slide

  14. Simple Rendering with Interpolation

    View Slide

  15. Binding properties
    ▪ use the brackets [] to bind to a property
    ▪ This creates a OneWay-Data Binding

    View Slide

  16. Binding events
    ▪ Use parentheses () to bind events to methods

    View Slide

  17. Add the FormsModule to your AppModule
    ▪ This allows you to use ngModel for TwoWay-Data
    Bindings

    View Slide

  18. TwoWay-Data Bindings
    ▪ You can see above that neither a DOM-property
    nor a DOM-event is involved => it’s pure Angular
    ▪ As Angular knows the bound property and the
    bound event

    View Slide

  19. TwoWay-Data Bindings

    View Slide

  20. Component Lifecylce Hooks
    ▪ You can hook into the life cycle of your component.
    Just implement these interfaces:
    ▪ OnInit - intialize your component and load data
    ▪ OnChanges - react to changes of input
    properties
    ▪ OnDestroy – perform cleanup actions

    View Slide

  21. Component Lifecylce Hooks

    View Slide

  22. Component Lifecylce Hooks

    View Slide

  23. Summary
    ▪ Angular Apps are component-based
    ▪ [()] => Bind a property two-way. FormsModule
    needs to be imported
    ▪ Lifecycle Hooks are used by implementing their
    interface

    View Slide

  24. Dynamic component loader

    View Slide

  25. Dynamic component loader
    ▪ Component templates are not always fixed
    ▪ May need to load components at runtime

    View Slide

  26. Dynamic component loader
    ▪ Before you can add components you have to define
    an anchor point to tell Angular where to insert
    components
    ▪ Can be done with a Directive or with a template

    View Slide

  27. Dynamic component loader

    View Slide

  28. Resolving component
    ▪ Resolve a ComponentFactory
    ▪ The ComponentFactory then creates an instance of
    each component
    ▪ With viewContainerRef we can tell Angular where
    to insert dynamic components
    ▪ To add the component to the template, you call
    createComponent() on ViewContainerRef.

    View Slide

  29. Resolving component

    View Slide

  30. Demo

    View Slide

  31. Summary
    ▪ ComponentFactory creates an instance of a
    component
    ▪ viewContainerRef defines where to insert the
    components

    View Slide

  32. Communication with a
    template

    View Slide

  33. Communication with a Template
    ▪ Data Binding
    ▪ Structural Directives
    ▪ Notifying the Component of User Changes

    View Slide

  34. Notifiyng the Component of User Changes
    ▪ Two-way Databinding with ngModelChange
    ▪ Getter/Setter in Two-way Databinding
    ▪ valueChanges observable

    View Slide

  35. Two-way Databinding with ngModelChange
    ▪ Normal two-way Databinding
    ▪ Two-way Databinding, the long form
    ▪ To interact or notify to the change, add a method

    View Slide

  36. Notifiyng the Component of User Changes
    ▪ Getter and Setter

    View Slide

  37. Angular Forms
    Template-Driven Forms
    ▪ Angular creates the form
    ▪ Defined in the template
    ▪ Access references with
    ViewChild
    Reactive Forms
    ▪ We create the form structure
    ▪ Define in the component
    ▪ No need for ViewChild

    View Slide

  38. ValueChanges observable: Template-Driven
    ▪ Even if input is not inside a form, we can access it
    via ViewChild

    View Slide

  39. ValueChanges observable: Reactive Froms
    ▪ Subscribe directly to the form control

    View Slide

  40. Summary
    ▪ Whenever possible, use bindings and structural
    directives
    ▪ They are simple, common and easy to understand
    for any other developer on the team
    ▪ Avoid using two-way Databinding the long way.
    ▪ Getter and Setters are a good alternative but
    require more lines of code
    ▪ Or subscribe to the valueChanges event

    View Slide

  41. Pause bis 10:15 Uhr.

    View Slide

  42. Demo

    View Slide

  43. ViewChild and ViewChildren

    View Slide

  44. Use Cases
    ▪ A component may need to interact with or get
    information about a specific element or directive
    on a template
    ▪ Example: A component needs to set the focus on a
    specific element

    View Slide

  45. Getting a Reference
    ▪ Javascript “old-school” way to access an element
    ▪ In Angular we use the ViewChild decorator

    View Slide

  46. ViewChild
    ▪ The selector can be an Angular Directive
    ▪ Custom directives
    ▪ Template Reference Variable

    View Slide

  47. ViewChild
    ▪ Template Reference Variable
    ▪ Template
    ▪ Use it on the AfterViewInit Lifecycle Hook. View has
    to be initialized and rendered first

    View Slide

  48. ViewChild – accessing ViewContainerRef
    ▪ There can be several instances of various types
    associated with the element tag
    ▪ ElementRef instance if there is no component
    applied, or the
    ▪ component instance if there is.
    ▪ If you want to get something different you need to
    explicitly specify using read.

    View Slide

  49. ViewChild – accessing ViewContainerRef

    View Slide

  50. ViewChildren
    ▪ Accessing multiple elements or directives on a Template
    ▪ Tracks changes in the DOM
    ▪ Same selectors but can have a set of variables

    View Slide

  51. Summary
    ▪ ViewChild/Children provides a native element
    property
    ▪ Or provides a reference to the directive’s data
    structures
    ▪ By default only available after the AfterViewInit
    Lifecylce Hook
    ▪ It has to be inside the DOM to evaluate it

    View Slide

  52. Demo

    View Slide

  53. Communicating through a
    service

    View Slide

  54. How do Services help the components
    ▪ Service as a box
    ▪ Temporarily store data
    ▪ To itself or to other components

    View Slide

  55. Typical Angular Application

    View Slide

  56. Typical Angular Application
    Update
    Update
    Event

    View Slide

  57. What is State?
    ▪ View State
    ▪ User Information
    ▪ Entity Data
    ▪ User Selection and Input
    ▪ …

    View Slide

  58. State Management
    With a state management system we would like to have:
    ▪ A single-source of truth of our applications state and
    ▪ encapsulate our business logic from our view logic

    View Slide

  59. State Management
    State
    Management with
    Notifcations
    Basic State
    Management
    Property Bag
    NgRx

    View Slide

  60. Property Bag
    ▪ A service with a property of values
    ▪ Service holds a bag of property values
    ▪ The component has getters and setters which
    interact directly with the service
    ▪ We always loose the properties from a component
    when we navigate away

    View Slide

  61. Retain the search values
    ▪ Scenario: A user enters a search, navigates to details
    and returns back => the search term is gone.
    ▪ Can also be done by QueryParams. Normally the
    better way.
    ▪ However, what if the search is huge and complex?
    ▪ Property Bag Service is a good alternative to
    QueryParams

    View Slide

  62. Param Service
    ▪ A simple service
    ▪ Component uses getter and setters

    View Slide

  63. Services
    ▪ Provide functionality across components
    Logging, Calculations, Data access, Data sharing, etc.
    ▪ Register it with the Angular Injector
    ▪ Inject into any component that needs it
    ▪ Normally, services are implemented as Singletons

    View Slide

  64. Service Scope and Lifetime
    ▪ Services can be registered on the component or
    module level
    ▪ Service scope: Defines which components can see
    and access the service
    ▪ The service lifetime depends on where the service is
    registered

    View Slide

  65. Demo

    View Slide

  66. Pause bis 11:30

    View Slide

  67. Summary: Property Bag
    ▪ Is great for retaining view state and user selections
    ▪ Also for sharing data and communicating state
    changes
    ▪ But any component can read the values and change
    it
    ▪ Components are only notified of state changes if
    they use template binding

    View Slide

  68. State Management
    State
    Management with
    Notifcations
    Basic State
    Management
    Property Bag
    NgRx

    View Slide

  69. Basic State Management Service
    ▪ Retrieving Entity Data (CRUD)
    ▪ Provide state values
    ▪ Data does not change very often in the backend, so
    do not load it every time
    ▪ Data is stored locally
    ▪ Observe state changes

    View Slide

  70. Data Sharing Service
    ▪ Only load data the first time. Then use local instances

    View Slide

  71. Data Sharing Service: GetAll
    ▪ Only load data the first time. Then use local instances

    View Slide

  72. Data Sharing Service: GetById
    ▪ Get instance from local array

    View Slide

  73. Data Sharing Service: Create
    ▪ Add it to the list if no error occurs

    View Slide

  74. Keeping State in Sync

    View Slide

  75. Track Selected SalesRegion
    ▪ A property with the selected SalesRegion.

    View Slide

  76. Track Selected SalesRegion
    ▪ A property with the selected SalesRegion

    View Slide

  77. Get selected SalesRegion
    ▪ Notify detail about the selected employee. A simple
    property does not work. For change detection a
    getter is appropriate. If everything is properly bound,
    it works automatically (pull).

    View Slide

  78. Get selected SalesRegion

    View Slide

  79. Summary: Basic State Management
    ▪ State Management Service for retrieving, managing
    and storing state
    ▪ Share between components
    ▪ Retains and shares state values
    ▪ Minimizes hits to the backend server
    ▪ Provides changes notifications for bound values
    using a getter
    ▪ No explicit change notification
    ▪ State is not immutable

    View Slide

  80. State Management
    State
    Management with
    Notifcations
    Basic State
    Management
    Property Bag
    NgRx

    View Slide

  81. State Management with Notifications
    ▪ Add notifications to the service
    ▪ Broadcasting service notifications
    ▪ EventEmitter is similar but not recommended
    ▪ Can be done with Subjects
    ▪ Or with BehaviorSubjects

    View Slide

  82. Subject
    ▪ The key purpose is to send out notifications
    ▪ Is a special type of an observable which can
    multicast an event to multiple subscribers
    ▪ It is also an observer

    View Slide

  83. Use the Subject
    ▪ Notify about the change
    ▪ Expose only the readonly observable

    View Slide

  84. Use the Subject
    ▪ Now we can subscribe to the observable

    View Slide

  85. BehaviorSubject
    ▪ When subscribing to a BehaviorSubject, you get the
    last value of the chain
    ▪ Everything else is exactly as with a regular Subject

    View Slide

  86. Cleaning up Subscriptions
    ▪ To prevent memory leaks, we should unsubscribe
    from the observable if we are finished using it.

    View Slide

  87. Demo

    View Slide

  88. Summary: State Management with
    Notifications
    ▪ Use Subject when notifications are more than just
    changes to bound properties
    ▪ It does not need a subject if notifications are not
    required
    ▪ Especially not if notifications are only for changes
    to bound properties
    ▪ Use Subject if there is no initial value

    View Slide

  89. Redux Pattern
    Component
    Action
    Redcuers
    State
    Dispatch
    Notify
    Sent
    Create new state
    Effect
    Rest
    Service

    View Slide

  90. Angular Elements

    View Slide

  91. «Angular is ideal for building complete applications, and
    our tooling, documentation and infrastructure are
    primarily aimed at this case.»
    Rob Wormald, Angular Team

    View Slide

  92. Platform
    Dependency
    Injection
    Decorators Zones
    Compile Binding Render
    Material Mobile Universal
    CLI
    Language
    Service
    Augury
    ngUpdate
    Router
    Animation
    i18n

    View Slide

  93. «[…] but it’s quite challenging to use in
    scenarios that don’t fit that specific Singe Page Application
    model.»
    Rob Wormald, Angular Team

    View Slide

  94. Use Cases
    ▪ Enhancing existing HTML Pages
    ▪ Content Management Systems integration
    ▪ Use components in other environments or
    frameworks
    ▪ Microfrontends
    ▪ Migrating Legacy Apps

    View Slide

  95. View Slide

  96. Web Components

    View Slide

  97. Web Components
    Web Components are a set of features added by the W3C
    HTML Template
    Shadow DOM
    HTML Imports
    Custom Elements

    View Slide

  98. Custom Elements
    Custom elements share the same API surface as native
    DOM objects:
    ▪ Attributes
    ▪ Properties
    ▪ Methods
    ▪ Events

    View Slide

  99. Create and Define a Custom Element

    View Slide

  100. Reactions

    View Slide

  101. Attributes

    View Slide

  102. Properties
    let tile = document.querySelector('weather-tile');
    tile.location = 'Hamburg';

    View Slide

  103. Custom Event
    let tile = document.querySelector('weather-tile');
    tile.addEventListener('location-change', event => { ... });

    View Slide

  104. Custom Elements in Angular
    => Angular has been designed for this

    View Slide

  105. Enter Angular Elements
    Provides a bridge from angular concepts to web
    components.
    @HostBinding() => Attributes
    @Input() => Properties
    @Output() => CustomEvents
    Lifecycle Hooks => Reactions

    View Slide

  106. Getting started

    View Slide

  107. First Steps
    ▪ Update Angular CLI
    ▪ Create a new Angular CLI project
    ▪ Add support for angular elements
    ▪ Generate new application or component
    ng new angularElements
    ng add @angular/elements
    ng g application

    View Slide

  108. Component

    View Slide

  109. Module

    View Slide

  110. Polyfills

    View Slide

  111. Polyfills
    ▪ Angular Elements comes with a polyfill
    ▪ However, it just can be used with browsers
    supporting EcmaScript 2015 and above
    ▪ For older browsers, try the polyfills from the
    following package:
    @webcomponents/webcomponentsjs

    View Slide

  112. Create a single bundle & shrink bundles
    ▪ Use ngx-build-plus for single-bundles and more tree-
    shakable code
    ▪ Install package ngx-build-plus
    ▪ Update angular.json builder setting to
    "ngx-build-plus:build"
    ▪ Get rid of zone.js (!!!!)

    View Slide

  113. Load a Web Component dynamically

    View Slide

  114. Load a Web Component dynamically

    View Slide

  115. Dependency Injection
    Plattform Injector
    (Renderer)
    Module Injector
    (Services)
    Component Injector
    (ElementRef)

    View Slide

  116. DI in Angular Elements
    Plattform Injector
    (Renderer)
    Module Injector
    (Services)
    Element Injector
    (ElementRef)
    Element Injector
    (ElementRef)

    View Slide

  117. Module

    View Slide

  118. Shadow DOM

    View Slide

  119. Outlook ??

    View Slide

  120. Demo

    View Slide

  121. Weitere Informationen
    • github.com/gassmannT/dashboard-component-workshop
    • thomasgassmann.net
    • swissangular.com
    • trivadis-training.com/de/training/kurse-nach-markttrends/web-
    development
    • angular-academy.ch

    View Slide

  122. Vielen Dank!
    Thomas Gassmann
    [email protected]
    thomasgassmann.net
    @gassmannT

    View Slide

  123. View Slide