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?
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With