
Custom Elements
Shadow DOM
HTML imports
HTML Template
Angular elements are Angular components packaged as custom elements, a web standard for defining new HTML elements in a framework-agnostic way.
class Countdown extends HTMLElement {
connectedCallback() {
const template = `
<button class="countdown-start">Start the countdown</button>
<span class="seconds-left"></span>
`;
this.innerHTML = template;
// Useful references
this.button = this.querySelector('.countdown-start');
this.secondsDisplay = this.querySelector('.seconds-left');
// Initialize
this.button.addEventListener('click', () => this.handleClick());
}
handleClick() {
if(this.hasAttribute('seconds')) {
this.seconds = +this.getAttribute('seconds');
} else {
this.seconds = 10;
}
this.updateTimer();
this.button.disabled = true;
this.button.innerHTML = 'YOU DID IT';
this.updateTimer();
const counter = window.setInterval(() => {
this.seconds--;
this.updateTimer();
if (this.seconds === 0) {
window.clearInterval(counter);
console.info('BOOM');
this.dispatchEvent(new Event('boom'));
}
}, 1000);
}
updateTimer() {
this.secondsDisplay.innerHTML = this.seconds;
}
}connectedCallback => componentDidMount
disconnectedCallback => componentWillUnmount
attributeChangedCallback => componentDidUpdate
adoptedCallback => ¯\_(ツ)_/¯
<!-- Add it to the DOM -->
<countdown-timer seconds=20></countdown-timer>
<script>
// Define the element on the global CustomElementRegistry
window.customElements.define('countdown-timer', Countdown);
// Listening to the output event
document.querySelector('countdown-timer')
.addEventListener('boom', function(event) {
console.log('BOOM');
});
</script>import { Component, OnInit, Input, Output, EventEmitter, ViewEncapsulation } from '@angular/core';
@Component({
selector: 'ng-wolf',
template: `
<img [src]="avatar" (click)="reveal($event)" alt="Wolf" />
`,
styles: [`
img {
max-width: 100%;
height: auto;
}
`],
encapsulation: ViewEncapsulation.Native
})
export class WolfComponent implements OnInit {
@Input()
name: string;
@Input()
avatar: string;
@Output()
revealed = new EventEmitter();
constructor() { }
ngOnInit() {
}
reveal(event) {
this.revealed.emit(`You found me. I am ${this.name} the WolfComponent.`);
}
}~60kb in this case
https://www.webcomponents.org/introduction
https://angular.io/guide/elements
https://github.com/webcomponents/react-integration
https://custom-elements-everywhere.com/
https://medium.com/@tomsu/building-web-components-with-angular-elements-746cd2a38d5b