Extend Elements with Behaviors

Our Web Components library has a feature, which allows you to dynamically extend a Custom Element with additional behaviors. We call them Modules. To add a new module, you have to call the 'addModule' method. In this blog, we will show you how to create a new module, which adds a 'color' property to a Custom Element. We will call it 'ColorModule'.

class ColorModule  {
	 static get properties() {
		 const properties =
			 'color': {
				 value: 'red',
				 type: 'string',
				 observer: 'setColor'
		 return properties;
	ready() {
		this.ownerElement.$.root.style.color = this.color;
	setColor(oldColor, color) {
		this.ownerElement.$.root.style.color = this.color;

The 'ColorModule' defines a 'color' property. The default property value is 'red'. Whenever the 'color' property is changed, the 'setColor' method is invoked which applies the Color to the element.
The below code adds the Module to the 'smart-toggle'button' Custom Element.

window.Smart.Elements.whenRegistered('smart-toggle-button', function (proto) {
    proto.addModule(ColorModule, true);

Note that the second parameter is 'true'. This means that our 'ColorModule' will be added to all sub-classes of the 'smart-toggle-button' i.e 'smart-radio-button', 'smart-check-box' and 'smart-switch-button'. All these custom elements will have the 'color' property.
Usage example:

window.onload = function() {
    document.querySelector('smart-radio-button').color = "blue";

This entry was posted in HTML Elements, Javascript and tagged , , , , , , . Bookmark the permalink.

Leave a Reply