Teradata Engineering
Web Components
&
What is a web component?
- Custom Elements
- Shadow DOM
- HTML imports
- HTML Template
The important parts...
<script>
let template = document.querySelector('#your-component');
class YourComponent extends HTMLElement {
constructor() {
super();
let shadowRoot = this.attachShadow({mode: 'open'});
shadowRoot.appendChild(template.content.cloneNode(true));
}
}
customElements.define('your-component', YourComponent);
</script>
<template id="your-component">
<p>I'm in Shadow DOM.</p>
</template>
<style>
/* place your styles here */
</style>
Attribute Reflection
- declarative
- event based
Observing Attribute Changes
attributeChangedCallback(attributeName, oldValue, newValue)
Build
gulp.task('inline-resources', () => {
return gulp
.src(`${tmpFolder}/switcher/switcher.component.ts`)
.pipe(
replace(/(template\.innerHTML = `)(`;)/, (match, p1, p2) => {
const html = fs
.readFileSync(`${tmpFolder}/switcher/switcher.component.html`)
.toString()
.trim();
const cssResult = sass.renderSync({
file: `${tmpFolder}/switcher/switcher.component.scss`
}).css;
return `${p1}
<style>${cssResult.toString()}</style>
${html}
${p2}`;
})
)
.pipe(gulp.dest(`${tmpFolder}/switcher/`));
});
Using your components in Angular
Add a es5 shim to your project via .angular-cli.json (https://github.com/angular/angular-cli/wiki/stories-global-scripts)
"scripts": [
"../node_modules/@webcomponents/webcomponentsjs/custom-elements-es5-adapter.js"
]
Add a webcomponent polyfill to your polyfills.ts file for cross browser compatability IE etc.
Gotchyas!
@NgModule({
declarations: [
YourWebComponent,
],
exports: [
YourWebComponent,
],
schemas: [CUSTOM_ELEMENTS_SCHEMA],
})
export class YourWebModule { }
Don't add CUSOM_ELEMENTS_SCHEMA to main app module!
Using your web components in any other tech stack!
Our build is a glorified UMD (Universal Module Definition) bundler!
PROS / CONS
- Can work cross tech stack (>IE11)
- Is a W3C specification
- Is the model for Angular Components
- Interoperability with Angular
- Pretty light weight (20kb gzip)
- Some specifications are still evolving
- Needs a build
- Learning curve (like anything new, but also minimal as it's native JS mostly after the boilerplating)
thanks!
questions?
References
https://developers.google.com/web/fundamentals/web-components
https://www.webcomponents.org
Web Components!
By ianqueue
Web Components!
- 354