Polymer Custom Elements
Polymer.js framework facilitates you to create custom elements using standard HTML elements.
Features of custom elements:
You can define the custom element using ES6 class. Class can be associated with the custom element like this:
We can use custom element as standard element:
Note: Custom element name should start with a lower case letter and contain a dash between the names.
Custom Element Lifecycle
Custom element lifecycle provides a set of custom element reactions which are responsible for changing in element lifecycle
Following is a list of those custom element reactions:
We can use custom elements before defining them by specification and any existing instances of an element will be upgraded to the custom class by adding a definition to that element.
The custom element state contains the following values -
Uncustomized: The valid custom element name is either a built-in element or an unknown element, which cannot become a custom element.
Undefined: The element can have a valid custom element name, but it cannot be defined.
Custom: The element can have a valid custom element name, which can be defined and upgraded.
Failed: Trying to upgrade the failed element of an invalid class.
Define an Element
We can define a custom elements by creating a class which extends Polymer.Element and it passes the class to customElements.define method. The class contains is getter method that returns a HTML tag name of the custom element.
Import And APIs
We can define Polymer elements by specifying the three HTML imports:
polymer-element.html: It is used to specify the Polymer Element base class.
legacy-element.html: It is used to extend Polymer.Element using Polymer. Legacy Element base class and adds 1.x compatible legacy API. It also creates hybrid elements by defining the legacy Polymer() factory method.
polymer.html: It is used to comprise the Polymer base classes along with helper elements, which were included in the 1.x polymer.html.
Define an Element in the Main HTML Document
The HTMLImports.whenReady() function is used to define an element in the main HTML document.
Let's take an example to define an element in the main HTML document. Create an index.html file and use the following code:
Now create a custom element called define-element.html and use the following code.