Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create Angular custom elements with Angular universal: SSR

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?

like image 861
j4rey Avatar asked Jul 16 '18 09:07

j4rey


1 Answers

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
}
like image 159
Nicola Tommasi Avatar answered Sep 21 '22 11:09

Nicola Tommasi