Uncategorized

Angular takes on Web Components

This series of blog posts which I have converted from Youtube videos. I personally have really enjoyed these videos so in order to textually document them, these are essentially some screenshots and rough notes organised. 

This particular post is based on the awesome Rob Wormald AnuglarMix 2017 talk. It can be found on the link https://www.youtube.com/watch?v=ljsOPm4MMEo

Because of Angular’s vast capabilities, the developers are looking for additional web related work that can be done through it. Angular could be required to use for enhancement of static web pages. This is done through AngularJS already on some websites. The HTML pages are written then AngularJS and Bootstrap is used to provide enhancement in the code. This could be done by adding ‘ng-app’ tag i.e. the ‘ng-app’ attribute to the page. It was a popular functionality among many web developers using AngularJS. It has a few drawbacks like compile performance such as less comprehensive error message generation etc.

But still, this functionality was quite useful and isn’t unfortunately available in the newer version of Angular. Angular Elements is hopefully expected to change that.

Enhancing Existing HTML Pages (CMS)

Other functionalities that are considered difficult in Angular is building Content Management Systems. This difficulty is present when there is a server-side logic with different pages for WordPress, Drupal etc. The purpose of WordPress and Drupal is to implement the HTML and once the application boots up, provides an interactive experience. Though this is possible but still is a difficult task to accomplish using the present capabilities of Angular. Using Angular in CMS pages is termed as using Angular components in non-Angular context. To achieve this task, the most important thing is having complete and correct knowledge of Angular. Understanding how Angular works and about its component model is along with modules and bootstrapping is needed to use it in this context. Thus it requires a lot of overhead as per deemed in the case on the Angular docs.

Considering the example of Angular documentation, most of the data is mostly in the form text and isn’t interactive, this situation on the Angular website is dealt by the Angular application. The outer shell of the Angular i/o is an Angular application. But all of the documents are HTML and are fetched and inserted into the page. Though this seems like a static text work, has an element of interactivity in it.

Heterogeneous Environment

AngularJS swept the entire developer environment on the web with its launch 5 years ago. And Angular and similar products were being used for development at the time. And now the JavaScript community has grown by leaps and bounds. With people involved with React, Polymer, JQuery etc, it is believed that a new JavaScript frame is being launched every 5 minutes. Some examples of Angular environments are:

  • AngularJS
  • React
  • Polymer
  • JQuery
  • Vanilla DOM

But because of these heterogeneous environments, it is difficult to create interaction between them. Suppose in a React application, there is a need for the addition of Angular component from a different application using Vanilla DOM. This is a difficult situation to handle.

Angular Embedded

This interaction between heterogeneous environments is a common requirement during development using Google APIs etc. Suppose there is a need to run sentiment analysis API use it on a web application and they are using Angular component. This cross development Angular embedding is required for cross-team sharing, Web context and building stuff with Angular for non-Angular developers.

The Angular I/O documentation is typically set to be easily understood and easy to grasp with navigation bar on the side. There’s a tab panel for HTML which is written in Angular. An HTML, which is not Angular, can be loaded into it and a widget can be bootstrapped into that HTML.

Widgets that are present on the Angular repo can be configured as per need. During coding, there is difficulty connecting static HTML with Angular components and there is also a need for manual management..

Web Components

Web components are made of four specifications:

  • HTML Templates  <template> similar to ng tags
  • Shadow DOM  is view encapsulation.native under the hood
<my –app>

   <#shadow-root>

        <h1 class=”title”></h1>

   </shadow-root>

</my-app>
  • HTML Imports is only imported in few of the browsers but isn’t used anymore.
<html>

   <head>

       <link rel=”import”  href=”polymer.html”>

       </link>

   </head>

</html>
  • Custom Elements is an important part of web component.
<my-app>

     <my-header></my-header>

     <main-view></main-view>

</my-app>

Custom Elements

It is a standard way to define a “web component” and it takes some logic and turns it into proper HTML. V0 was present in early days of Angular but was abandoned later on. V1 has been supported by many browsers like Chrome and Safari technical preview with Polyfillable back to IE10. The above custom element can be placed inside HTML tags.

<fancy-datepicker> </fancy-datepicker>

Elements

The custom element class can be created which defines the task performed by the element. It is registered with the custom element API using the ‘customElements’ keyword.

class FancyDatePicker extends HTMLElement {}

customElements

.define(‘fancy-datepicker’ , FancyDatePicker);

Attributes

Attributes is an important API; the custom elements monitor the change in these attributes. They have a lifecycle hook that plugs in to generate a notification on change. The code presents below monitors and generates a notification on the change in date.

class FancyDatePicker extends HTMLElement {

        static observedAttributes = [current-date];

        attributeChangedCallback( oldV, newV, key) {

         //update the DOM somehow

       }

}

<fancy-datepicker

current-date = “10/10/2017”>

</fancy-datepicker>

Properties

Properties also work the same way and has a getter and setter so that when it sets on an element an event takes place.

class FancyDatePicker extends HTMLElement {

        set currentDate(value){

         //update the DOM somehow

       }

Get currentDate(){ … }

}

And this can also be done imperatively like:

const picker = document.querySelector(‘fancy-datepicker’);

picker.currentDate = new Date();

Events

Custom Elements can also emit events like native Dom elements emit events. New events can be created and dispatched.

class FancyDatePicker extends HTMLElement {

emitDateChange(){

      let dateChangeEv = new CustomEvent(‘date-change’,{details});

      this.dispatchEvent(dateChangeEv);

      }

}

Then the event can be queried to add event:

const picker = document.querySelector(‘fancy-datepicker’);

const onDateChange = (date) => console.log(date);

picker.addEventListener(‘date-change’,onDateChange);

These are commonly known to web developers.

Life cycle Hooks

Life cycle Hooks are also present such as connected call backs, disconnected callbacks etc. These Fire when the elements get inserted or removed from the DOM with change callback and adopted callback.

class FancyDatePicker extends HTMLElement {

       connectedCallback(){ … }

       disconnectedCallback(){ … }

       attributeChangedCallback( oldV , newV , key ){ … }

       adoptedCallback(){ … }

      }

}

Custom Elements in Angular:

By design custom elements work in Angular. By Placing these elements inside the Angular template, standard Angular template syntax can be used for attributes, properties, events etc.

<my-Angular-app>

      <fancy-input

         [attr.foo]=”someString”

         [someProp]=”someProp”

         (some Event)=”doStuff()”?

      </fancy-input>

</my-Angular-app>

What if everything could be done as a web component? The Google team is currently working on a project to reference component URLs. Angular provides some other functionalities which are not even closely related to web components. The project can be accessed through:

Github – GoogleChromeLabs (How-to Components)

Angular Elements are Angular Components Packaged as Custom Elements

The new Angular Lab project is based on the idea that an Angular element is an Angular component packaged as a custom element. This means that there is self-bootstrapping allowed on HTML pages without any query or call required. Basically, an Angular component is hosted inside a Dom element similar to the way it works in Angular involving ‘Host Listeners’ and ‘Host Bindings’. They are used as a bridge between DOM APIs and Angular APIs. Zones are optional and thus makes it simpler for certain applications not using zones. Basically, it is an Angular component on the inside and web component custom element on the outside. It can be used by anyone who understands the working. Custom elements require more work as compared to Angular elements is less clean.

Example: Progress Bar

Some interesting things you can do with this Progress bar:

Only the knowledge of DOM elements is required to make Web Components without having to know about Angular. These work similar to widgets which can be modified and used. These can also be done on an enterprise level for complete business applications. Two distinct instances of application provide code reusability and create a model for different uses such as CMS, widgets etc and make it more flexible.


Leave a Reply

Your email address will not be published. Required fields are marked *