2

I have installed ng2-pdf-viewer to show documents within angular 6 app.

To make it work I need to import PdfViewerModule in FeatureModule where I want to use <ng2-pdf-viewer> component.

The problem is in PdfViewerModule, it calls Element and Window object inside its functions and it crushes when serving node server.js.

At the moment my modules are imported like this:

BrowserModule > AppModule > FeatureModule > PdfViewerModule(declare <ng2-pdf-viewer>)

Usually I can solve such issues by importing such specific module directly into BrowserModule and supply ServerModule with some customly created mocked module which might declare samely named <ng2-pdf-viewer> mock. The solution I thought about is to import PdfViewerModule in BrowserModule directly, like this:

BrowserModule(imports PdfViewerModule) > AppModule > FeatureModule

but in this case components of FeatureModule cant access <ng2-pdf-viewer> in their templates because it is not declared.

Is there a way to isolate PdfViewerModule from server-side execution, but keep its declarations? Maybe there is absolutely diffrent approach fir such cases?

Thank you in advance! :)

1 Answers1

0

I think this should do the trick.

<ng2-pdf-viewer *ngIf="isBrowser"></ng2-pdf-viewer>

isBrowser: boolean;

constructor(@Inject(PLATFORM_ID) private platformId: string) {
   this.isBrowser = isPlatformBrowser(platformId);
}

The *ngIf directive should prevent your PDF renderer to execute

Edit: that doesn't work because the browser javascript code executes even before the component initialization (in the module declaration)

As you already thought, you can try to adapt this solution Need BrowserAnimationsModule in Angular but gives error in Universal to your needs, you'd have an AppBrowserModule that imports AppModule plus another module that you'd create and that would wrap the PdfViewerModule, the components that use it and their associated routes.

Guerric P
  • 30,447
  • 6
  • 48
  • 86
  • same problem `node server.js` causes `webpack:///./node_modules/pdfjs-dist/build/pdf.js?:1080` `if (typeof Element.prototype.remove !== 'undefined') {` – Arseniy Shelestyuk Nov 06 '18 at 10:37
  • The non-browser JS code from this module executes during the build or during execution? – Guerric P Nov 06 '18 at 10:38
  • during execution `ReferenceError: Element is not defined` – Arseniy Shelestyuk Nov 06 '18 at 10:39
  • 1
    Ok so the problem comes from this line: https://github.com/VadimDez/ng2-pdf-viewer/blob/5f7237ed432cab08fda652810385434868017260/src/app/pdf-viewer/pdf-viewer.module.ts#L7 indeed you have no other choice than conditionnally import the module. And I don't know any way for doing that, except maybe lazy-loading but I'm not sure if it works on server side. – Guerric P Nov 06 '18 at 10:54