How to create Angular custom elements with Angular universal: SSR
Asked Answered
G

1

8

I am trying to create an Angular app with Angular Universal: SSR and Custom Elements.

I downloaded the sample code available in Angular Universal: SSR and added the following lines of code to for Custom Elements in AppModule's constructor

const ele = createCustomElement(AppComponent, {injector});
customElements.define('custom-ele', ele);

It is building just fine, but when I try to serve it I am getting the following error

...universal\dist\server.js:66760
var elProto = Element.prototype;

ReferenceError: Element is not defined
at Object.<anonymous> (...universal\dist\server.js:66760:15)
at __webpack_require__ (...universal\dist\server.js:20:30)
....

Is it because Element is a browser-only native objects, and since its on Server Side it won't be able reference browser-only native objects? Is there a work around?

Grampus answered 16/7, 2018 at 9:42 Comment(0)
C
6

You're right, Angular Elements aren't supported by Angular Universal yet. The error is due to this import:

import {createCustomElement} from '@angular/elements';

In the meanwhile, there's a workaround you can use, you can conditionally import createCustomElement in this way:

After your imports just declare the require:

declare var require: any;

Then use the isPlatformBrowser method from @angular/common to import createCustomElement only in the client:

if (isPlatformBrowser(platformId)) {
  const { createCustomElement } = require('@angular/elements');
  // you can use createCustomElement here
}
Chippy answered 26/7, 2018 at 14:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.