Week 7 | Type-extension Element

polymer 1.0
Mon Oct 10 2016

In Polymer we don’t only declare new elements but can extend native elements as well.

In our example I have a native input element. We can extend this by using the is=”hello-element” attribute. Then declare the prototype of HelloInput with the is: ‘hello-element’ and the extends: ‘input’ property.

To prove that we are extending the native element I’ll check if the “HelloElement” element is an instance of the HTMLInputElement prototype. Also, once created I’ll set the value to “hello there”.

If you run the demo => https://plnkr.co/edit/hweAJ7HEEE1xUCKKB9nx?p=preview you’ll notice that:

  1. It does truly extend the HTMLInputElementinputelement
  2. It changes the value of the input

helloinput

Demo Code Used

<!DOCTYPE html>
<html>
    <head>
      <script src="https://polygit.org/components/webcomponentsjs/webcomponents-lite.min.js"></script>
      <link rel="import" href="https://polygit.org/components/polymer/polymer.html" />
    </head>
    <body>
    <input type="text" is="hello-element" />
    <script>
      HTMLImports.whenReady(function () {
        HelloInput = Polymer({
            is: 'hello-element',
            extends: 'input',
            created: function(){
              this.value = "hello there";
            }
        });
        var el1 = new HelloInput();
        console.log(el1 instanceof HTMLInputElement);
        document.querySelector("body").appendChild(el1);
        var el2 = document.createElement('input', 'hello-element');
        console.log(el2 instanceof HTMLInputElement);
        document.querySelector("body").appendChild(el2);
      });
    </script>
    </body>
</html>

 

Full Stack Weekly Newsletter

A free weekly newsletter for full stack web developers!