Angular Universal, How to isolate module with declarations from server-side execution?

878 views Asked by At

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

There are 1 answers

4
Guerric P On

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.