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.

F8980be26d3f8c298c19e3e30ac0dbe1?s=128

Thomas Gassmann

October 12, 2020
Tweet

Transcript

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

    2020 Thomas Gassmann
  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.
  3. Agenda • Introduction into Components • Dynamic component loading •

    Communicating with a Template • ViewChild and ViewChildren • Communicating through a service • Angular Elements.
  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
  5. Thomas Gassmann Principal Consultant, Trainer, Speaker thomas.gassmann@trivadis.com thomasgassmann.net @gassmannT

  6. What we are building

  7. Introduction

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

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

    Component Component Component
  10. None
  11. None
  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
  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
  14. Simple Rendering with Interpolation

  15. Binding properties ▪ use the brackets [] to bind to

    a property ▪ This creates a OneWay-Data Binding
  16. Binding events ▪ Use parentheses () to bind events to

    methods
  17. Add the FormsModule to your AppModule ▪ This allows you

    to use ngModel for TwoWay-Data Bindings
  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
  19. TwoWay-Data Bindings

  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
  21. Component Lifecylce Hooks

  22. Component Lifecylce Hooks

  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
  24. Dynamic component loader

  25. Dynamic component loader ▪ Component templates are not always fixed

    ▪ May need to load components at runtime
  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
  27. Dynamic component loader

  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.
  29. Resolving component

  30. Demo

  31. Summary ▪ ComponentFactory creates an instance of a component ▪

    viewContainerRef defines where to insert the components
  32. Communication with a template

  33. Communication with a Template ▪ Data Binding ▪ Structural Directives

    ▪ Notifying the Component of User Changes
  34. Notifiyng the Component of User Changes ▪ Two-way Databinding with

    ngModelChange ▪ Getter/Setter in Two-way Databinding ▪ valueChanges observable
  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
  36. Notifiyng the Component of User Changes ▪ Getter and Setter

  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
  38. ValueChanges observable: Template-Driven ▪ Even if input is not inside

    a form, we can access it via ViewChild
  39. ValueChanges observable: Reactive Froms ▪ Subscribe directly to the form

    control
  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
  41. Pause bis 10:15 Uhr.

  42. Demo

  43. ViewChild and ViewChildren

  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
  45. Getting a Reference ▪ Javascript “old-school” way to access an

    element ▪ In Angular we use the ViewChild decorator
  46. ViewChild ▪ The selector can be an Angular Directive ▪

    Custom directives ▪ Template Reference Variable
  47. ViewChild ▪ Template Reference Variable ▪ Template ▪ Use it

    on the AfterViewInit Lifecycle Hook. View has to be initialized and rendered first
  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.
  49. ViewChild – accessing ViewContainerRef

  50. ViewChildren ▪ Accessing multiple elements or directives on a Template

    ▪ Tracks changes in the DOM ▪ Same selectors but can have a set of variables
  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
  52. Demo

  53. Communicating through a service

  54. How do Services help the components ▪ Service as a

    box ▪ Temporarily store data ▪ To itself or to other components
  55. Typical Angular Application

  56. Typical Angular Application Update Update Event

  57. What is State? ▪ View State ▪ User Information ▪

    Entity Data ▪ User Selection and Input ▪ …
  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
  59. State Management State Management with Notifcations Basic State Management Property

    Bag NgRx
  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
  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
  62. Param Service ▪ A simple service ▪ Component uses getter

    and setters
  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
  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
  65. Demo

  66. Pause bis 11:30

  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
  68. State Management State Management with Notifcations Basic State Management Property

    Bag NgRx
  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
  70. Data Sharing Service ▪ Only load data the first time.

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

    time. Then use local instances
  72. Data Sharing Service: GetById ▪ Get instance from local array

  73. Data Sharing Service: Create ▪ Add it to the list

    if no error occurs
  74. Keeping State in Sync

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

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

  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).
  78. Get selected SalesRegion

  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
  80. State Management State Management with Notifcations Basic State Management Property

    Bag NgRx
  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
  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
  83. Use the Subject ▪ Notify about the change ▪ Expose

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

    observable
  85. BehaviorSubject ▪ When subscribing to a BehaviorSubject, you get the

    last value of the chain ▪ Everything else is exactly as with a regular Subject
  86. Cleaning up Subscriptions ▪ To prevent memory leaks, we should

    unsubscribe from the observable if we are finished using it.
  87. Demo

  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
  89. Redux Pattern Component Action Redcuers State Dispatch Notify Sent Create

    new state Effect Rest Service
  90. Angular Elements

  91. «Angular is ideal for building complete applications, and our tooling,

    documentation and infrastructure are primarily aimed at this case.» Rob Wormald, Angular Team
  92. Platform Dependency Injection Decorators Zones Compile Binding Render Material Mobile

    Universal CLI Language Service Augury ngUpdate Router Animation i18n
  93. «[…] but it’s quite challenging to use in scenarios that

    don’t fit that specific Singe Page Application model.» Rob Wormald, Angular Team
  94. Use Cases ▪ Enhancing existing HTML Pages ▪ Content Management

    Systems integration ▪ Use components in other environments or frameworks ▪ Microfrontends ▪ Migrating Legacy Apps
  95. None
  96. Web Components

  97. Web Components Web Components are a set of features added

    by the W3C HTML Template Shadow DOM HTML Imports Custom Elements
  98. Custom Elements Custom elements share the same API surface as

    native DOM objects: ▪ Attributes ▪ Properties ▪ Methods ▪ Events
  99. Create and Define a Custom Element

  100. Reactions

  101. Attributes <weather-tile location="A"></weather-tile>

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

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

    ... });
  104. Custom Elements in Angular => Angular has been designed for

    this
  105. Enter Angular Elements Provides a bridge from angular concepts to

    web components. @HostBinding() => Attributes @Input() => Properties @Output() => CustomEvents Lifecycle Hooks => Reactions
  106. Getting started

  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 <NAME>
  108. Component

  109. Module <weather-tile></weather-tile>

  110. Polyfills

  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
  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 (!!!!)
  113. Load a Web Component dynamically

  114. Load a Web Component dynamically

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

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

    Element Injector (ElementRef) Element Injector (ElementRef)
  117. Module

  118. Shadow DOM

  119. Outlook ??

  120. Demo

  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
  122. Vielen Dank! Thomas Gassmann thomas.gassmann@trivadis.com thomasgassmann.net @gassmannT

  123. None