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 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.
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.
Web Components mainly consists of three main technologies.
- HTML Templates
- Custom Elements
- Shadow DOM
Custom Elements + Shadow DOM
Using Web Components in APEXTo 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.
- Script tag has type attribute with module as it's value.
Adding User Interaction
- Name: Display Country Data (or any proper name)
- Event: Change
- Selection Type: jQuery Selector
- jQuery Selector: input[name=P35_COUNTRIES]
- True Action:
- Code: As shown below
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.