Page file
page.js
Web component is imported in this file
import { Component } from '@webformula/core';
/* HTML imports will bundle with the build */
import html from './page.html';
// imported component
import './component.js';
export default class extends Component {
static title = 'Page'; // html page title
static html = html; // you can set the html from and import or use the template method (see below)
constructor() {
super();
}
// this can be used in place of import the html file
template() {
return /*html*/`
<div>Page Content</div>
<!-- custom component -->
<custom-button>Click</custom-button>
`;
}
}
Component file
component.js
<!-- component.html -->
<button><slot></slot></button>
import { Component } from '@webformula/core';
import html from './component.html'; // automatically bundles
class CustomButton extends Component {
static html = html; // hook up imported html. Supports template literals (undefined)
/**
* Defaults to false.
* If this is false then the component will render directly in root element
*/
static useShadowRoot = true;
/**
* Defaults to true.
* Use global template element
* This should be set to false if the template is dynamic (<div>${this.var}</div>)
*/
static useTemplate = true;
// need to bind events to access `this`
#onClick_bound = this.#onClick.bind(this);
constructor() {
super();
}
afterRender() {
this.#root.querySelector('button').addEventListener('click', this.#onClick_bound);
}
disconnectedCallback() {
this.#root.querySelector('button').removeEventListener('click', this.#onClick_bound);
}
#onClick() {
console.log('Custom button component clicked!');
}
}
// define web component
customElements.define('custom-button', CustomButton);
Interacting with component elements
<!-- index.html -->
<body>
<custom-webcomponent></custom-webcomponent>
</body>
<!-- component.html -->
<button onclick="this.closest('custom-webcomponent').clickIt()">Click it direct</button>
<button id="eventlistener-button">Click it event listener</button>
import { Component } from '@webformula/core';
import html from './component.html'; // automatically bundles
class CustomWebcomponent extends Component {
static html = html; // hook up imported html. Supports template literals (undefined)
// need to bind events to access `this`
#onClick_bound = this.clickIt.bind(this);
varOne = 'var one';
constructor() {
super();
}
afterRender() {
this.#root.querySelector('#eventlistener-button').addEventListener('click', this.#onClick_bound);
}
disconnectedCallback() {
this.#root.querySelector('#eventlistener-button').removeEventListener('click', this.#onClick_bound);
}
clickIt() {
console.log('click it!');
}
}
// define web component
customElements.define('custom-webcomponent', CustomWebcomponent);