Skip to main content

Web Components in Oracle APEX

Few years back, I have learned about Web Components. However, I did not get a chance to work on Web Components yet. It's been on my do to list to experiment Web Components, especially with in APEX. My current staycation gave me an opportunity to do this experiment.

Web Components

Web Components is a suite of different technologies allowing you to create reusable custom elements — with their functionality encapsulated away from the rest of your code — and utilize them in your web apps.

In other words, using Web Components, we can create custom elements which are completely self contained with all HTML, CSS and JavaScript (JS) encapsulated in one place. And then we can use these new custom element in our web applications with out the risk of code conflicts. Functionality wise, they are similar to jQuery widgets, however to implement Web Components we don't need any additional libraries, all modern browsers natively support underlying technologies. If you are new to Web Components, then I suggest you to go through Web Components Crash Course video or this article. Above quoted definition is taken from this article. Example we are going to discuss is inspired from the above crash course video.

For the demo purpose, let's consider an example. We want to create a new custom element country-info with an attribute countrycode. When we specify countrycode, then this element should display basic information about the country, by making call to an existing RESTful API.

HTML Source

<country-info countrycode="IN"></country-info>

Target Output

web component example

Web Components mainly consists of three main technologies.

  • HTML Templates
  • Custom Elements
  • Shadow DOM

HTML Templates

HTML templates uses new template tag. As the name says, these are just templates and code written inside template tag is not rendered during the page load. We can use templates to hold some HTML/CSS and later, when needed, we can use these templates using JS. You can read further about template element here

So, let's first create a template for our example.

// JavaScript code
// create template element
const template = document.createElement('template');
// Write HTML and CSS into the template
// with Shadow DOM, CSS defined here will be applicable to custom elements alone
// CSS defined at page level won't be applicable to custom elements
template.innerHTML = `
  <style>
  div.country-data {
    background: #F5F4F2;
    width: 400px;
    margin-bottom: 10px;
    border-bottom: purple 8px solid;
    padding: 4px;
  }
  div.country-data h2{
    color: purple;
  }
  </style>
  <div class="country-data">
    <h2></h2>
    <div class="population">Population: <span></span> Millions</div>
    <div class="area">Area: <span></span> thousand sq.km.</div>
  </div>
`;

Custom Elements + Shadow DOM

Custom Elements are fully valid HTML elements with custom tag names and custom behavior defined using JS. To define a custom element, first we need to create a class that extends HTMLElement and then at the end we need to define custom element tag with the class name using window.customElements.define.

Using shadow DOM, we can isolate the custom element code from the page, so that page CSS, JS won't get conflicted (or used) for custom elements and vice-versa.

JS code for our example

// define class for the custom element
// general convention followed : if the custom element name is custom-element, then CustomElement is used as class name
// our custom element name is country-info, so lets define CountryInfo as class name
class CountryInfo extends HTMLElement {
  constructor() {
    // always call super first in constructor, so that the correct prototype chain is established.
    super();
    // attach Shadow DOM, this isolates the custom element
    this.attachShadow({ mode: 'open' });
    // clone the template content and append to shadowRoot
    this.shadowRoot.appendChild(template.content.cloneNode(true));
    // fetch country data from RESTful API
    // here, we are reading custom attribute countrycode value and using it as input for RESTful API call
    // fill template with data from RESTful API response
    fetch('https://apex.oracle.com/pls/apex/hari/country-data/country/' + this.getAttribute('countrycode')).then(response => response.json()).then(data => {
      this.shadowRoot.querySelector('h2').innerText = data.name;
      this.shadowRoot.querySelector('div.population > span').innerText = data.population;
      this.shadowRoot.querySelector('div.area > span').innerText = data.area;
    });
  }
}
// map country-info tag to use CountryInfo class
window.customElements.define('country-info', CountryInfo);

Using Web Components in APEX

To use this Web Component in APEX, let's save all this JS code to a file. I have copied template code, CountryInfo class code to a JS file. I have used same name for custom element and to the JS file. Having same name for both custom element and corresponding JS file is not a requirement, but it's a good practice. So, it our case, JS file name is country-info.js. Let's upload it in "APEX Application > Shared Components > Static Application Files" section.

Next, create an empty page in APEX and add below code in "Page > HTML Header" section.

<script type="module" src="#APP_IMAGES#country-info.js"></script>

Here, I would like to highlight two points
  • We are not using standard "Page > JavaScript > File URLs" section to load this JS file, instead we are writing script tag in HTML Header section.
  • Script tag has type attribute with module as it's value.
When we load JS file using as module, then functions, variables declared in the JS file will not be available in the global scope. For e.g. if you try to run below JS code in browser console, then you will get an error, even though template is declared in the JS file.

console.log(template.innerHTML);

As the aim of using Web Components is to completely make our code re-usable (just plug and play), it's better to use this approach to load Web Component JS files as modules. You can read more about JS Modules here.

Next, create a "Static Content" region with below source in the APEX page.

<country-info countrycode="IN"></country-info>

That's it and here is the demo. When we inspect country-info element using browser developer tools, we can see shadow-root and the template we have defined with country data.

Now, whereever we want to use our custom element, then we can simply include the country-info.js  file in page and we can write country-info HTML tag. Everything will magically works.

Adding User Interaction

Let's make this more interesting by adding some flexibility for users to choose which countries data they would like to see. For this, let's create a checkbox group item for countries, with Country Name as display value and Country Code as return value. Page item name in this demo is P35_COUNTRIES.

Now, modify the "Static Content" region source as below

<div id="country_data_container"></div>

Next, Create a Dynamic Action as below
  • Name:  Display Country Data (or any proper name)
  • When:
    • Event: Change
    • Selection Type: jQuery Selector
    • jQuery Selector: input[name=P35_COUNTRIES]
  • True Action:
    • Action: Execute JavaScript Code
    • Settings:
      • Code: As shown below
JS Code:
// get country code from the checkbox item
let countryCode = $(this.triggeringElement).val();
// get country-info tag for the countryCode, if it's previously added to the DOM
let countryNode = $("country-info[countrycode=" + countryCode + "]");
if ($(this.triggeringElement).is(':checked')) {
    // check if element already exists, then just show it
    if (countryNode.length == 1)
        countryNode.show();
    else
        // otherwise add it to DOM
        $('#country_data_container').append('<country-info countrycode="' + countryCode + '"></country-info>');
}
else {
    // unchecked, hide it
    countryNode.hide();
}

That's it and here is the demo.

Web Components in APEX

As I said above, this is a little experiment I did with the Web Components. This is a simple Web Component and we are not using template slots, custom element lifecycle callbacks etc. You can refer webcomponents.org to find out some useful and advanced Web Components published by others.

Conclusion

Web Components are clean and elegant. Once we build a web component, we can re-use it any web application without any fear of conflicts. As we have seen above, we can use Web Components in APEX in relatively simple way. However, to make use of APEX framework features like server-side conditions, authorization schemes etc. it is better to wrap Web Components as APEX plug-ins. Then we can get best of the both the worlds.

Have you used any Web Components in your APEX applications? What did you like most about using Web Components and what challenges have you faced while using them in APEX? Post your comments below.

Thank you.

Comments

Popular posts from this blog

Interactive Grid - Conditional Enable/Disable

In this blogpost, I am going to discuss few approaches using which we can conditionally enable/disable Interactive Grid (IG) column(s) based on other column(s) values. Note:    There is a bug  30801170  in APEX 19.2/20.1 with respect to "enable/disable" dynamic actions for IG columns. Workaround for this bug is provided at the end of this blogpost . This bug has been fixed in APEX version 20.2. Client Side Only Conditions If conditions to enable/disable are simple, then we can check those conditions easily on the client side. For e.g. let's consider IG on EMP table with following SQL Query. SELECT EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO FROM EMP Let's consider the requirement as - Enable "Commission" column only when JOB is equals to 'SALESMAN' and disable "Commission" column in all other cases. This can be done declaratively using dynamic actions (DA) DA "Enable/Disable Commission - 1" Create DA and give it a prope

Interactive Grid - Bulk Operation on Selected Rows

What's the Problem? Let's say you have an IG on employee table and you want to update selected employees commission based on user's input. Ideally, it should be very simple, where you can write UPDATE statement in page process and select IG region as "Editable Region" under "Execution Options" of the page process. But, when you select rows and submit page, you can see that, this process won't get executed! The reason is  Selection of 'Row Selector' check-boxes is not considered as row-change. Thus selected rows are not submitted to server. So, is there any work around?  Yes! Luckily there are lot of JavaScript (JS) APIs available to work with IG. If you are not already aware, you can refer "APEX IG Cookbook"  or  JavaScript API Reference documentation. If we continue with above Employee IG example, when user selects IG rows, enters "Commission %" and clicks on "Update Commission" button, then we can writ

Interactive Grid - Process Filtered Data on Server Side

Recently one of the APEX developers has reached out to me and asked if it's possible to capture filtered rows data of the Interactive Grid on the server-side and do some processing. In APEX 20.1, there is a new API APEX_IG , using which we can achieve this. Photo by Jakub Kapusnak on Unsplash The approach is very simple and straightforward. Get the internal region id based on the Static ID given for the IG region Get the last viewed report id based on region id Open query context for the region and report using region id and report id Fetch and loop through the rows using the query context Do something with fetched rows And finally, close the query context If you have already done this for interactive reports, then you should be already aware of these steps. The only difference here is, we use APEX_IG APIs instead of APEX_IR APIs. For the demo purpose, let's Build an Interactive Grid on EMP table and let's give it a Static ID as emp Create a Textarea page item with