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-world who="Unicorn"></hello-world>

You could setup component like shown below:

  1. Template file hello-world.html
<h1>Hello<span id="who"></span>!</h1>
  1. Javascript file hello-world.js
import { WebComponent } from 'web-component'

@WebComponent('hello-world', {
  template: require('./hello-world.html')
})
export class HelloWorld extends HTMLElement {
  constructor() {
    super();
    this._who = null;
  }

  static get observedAttributes() {
    return ['who'];
  }

  // Only called for the who attributes due to observedAttributes
  attributeChangedCallback(name, oldValue, newValue) {
    //don't need to do that decorator takes care of it for us
    //this._who = newValue;

    this._updateRendering();
  }

  connectedCallback() {
    //don't need to do that decorator takes care of it for us
    //if (this.hasAttribute('who')) {
    //  this._who = this.getAttribute('who');
    //}

    this._updateRendering();
  }

  //docorator automatically binds setter and getter methods for attributes

  //get who() {
  //  return this._who;
  //}

  //set who(v) {
  //  this.setAttribute("who", v);
  //}

  _updateRendering() {
    this.shadowRoot.querySelector('#who').textContent = `, ${this._who}`;
  }
}

Clone this wiki locally