DEV Community

John Peters
John Peters

Posted on • Updated on

Angular Components vs. Web Components in 10 minutes

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> =
     as any;

 // Listen to the close event
 popupEl.addEventListener('closed', () => 
 // Set the message
 popupEl.message = message;
 // Add to the DOM 
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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
  set message(message: string) {
    this._message = message;
    this.state = 'opened';
  get message(): string { return this._message; }
  _message: string;

  closed = new EventEmitter();
Enter fullscreen mode Exit fullscreen mode

Working Example Github Repo

Alt Text

Next: Exporting and importing an Angular Component as a Custom Element.

JWP2020 Angular Components vs. Custom Elements

Top comments (0)