The bridge between an Angular Component and a
WebComponent is 4 lines of code, placed in a service.
// This uses the new custom-element method to add the popup to the DOM.
showAsElement(message: string) {
// Create element
const popupEl: NgElement
&WithProperties<PopupComponent> =
document.createElement('popup-element')
as any;
// Listen to the close event
popupEl.addEventListener('closed', () =>
document.body.removeChild(popupEl));
// Set the message
popupEl.message = message;
// Add to the DOM
document.body.appendChild(popupEl);
}
This statement casts the created popup-element, to type NgElement which also contains WithProperties. The property names and values are within our Angular Component.
const popupEl: NgElement & WithProperties<PopupComponent> =
document.createElement('popup-element') as any;
The Angular Component Class 'withProperties'
// Class decorator stuff cut out for brevity
export class PopupComponent {
state: 'opened' | 'closed' = 'closed';
// Properties must use getter/setter syntax
@Input()
set message(message: string) {
this._message = message;
this.state = 'opened';
}
get message(): string { return this._message; }
_message: string;
@Output()
closed = new EventEmitter();
}
Next: Exporting and importing an Angular Component as a Custom Element.
JWP2020 Angular Components vs. Custom Elements
Top comments (0)