Skip to content

Hello World Example

Rafał Lorenz edited this page May 17, 2017 · 4 revisions

For example to create HelloWorld component and use it in your index.html file as follow:

<hello-worldwho="Unicorn"></hello-world>

You could setup component like shown below:

  1. Template file hello-world.html
<h1>Hello<spanid="who"></span>!</h1>
  1. Javascript file hello-world.js
import{WebComponent}from'web-component'
@WebComponent('hello-world',{template: require('./hello-world.html'),shadowDOM: true})exportclassHelloWorldextendsHTMLElement{constructor(){super();this._who=null;//this property is bind to element attribute becouse of observedAttributes}staticgetobservedAttributes(){return['who'];}// Only called for the who attributes due to observedAttributesattributeChangedCallback(name,oldValue,newValue){//this._who = newValue; this is handled by WebComponent decoratorthis._updateRendering();}connectedCallback(){// this is handled by WebComponent decorator// if (this.hasAttribute('who')) {// this._who = this.getAttribute('who');// }this._updateRendering();}// Decorator creates setter/getter methods for observed attributes//we do not have to do this// get who() {// return this._who;// }// set who(v) {// this.setAttribute("who", v);// }_updateRendering(){this.shadowRoot.querySelector('#who').textContent=`, ${this._who}`;}}

Clone this wiki locally