1

I'm facing an issue with Angular Universal throwing:

ERROR ReferenceError: document is not defined

This is Fullcalendar module that is trying to access document on server side, which does not exist on server. What I would like to do is to follow the guideline from Angular Git hub, from https://github.com/angular/universal/blob/master/docs/gotchas.md, saying:

If you have a component provided by a third-party that is not Universal-compatible out of the box, you can create two separate modules for browser and server (the server module you should already have), in addition to your base app module. The base app module will contain all of your platform-agnostic code, the browser module will contain all of your browser-specific/server-incompatible code, and vice-versa for your server module. In order to avoid editing too much template code, you can create a no-op component to drop in for the library component

I have created browser module:

 import { NgModule } from '@angular/core';
 import { AppComponent } from './app.component';
 import { AppModule } from './app.module';
 import { CalendarModule } from './calendar/calendar.module';

 @NgModule({

 imports: [
   AppModule,
   CalendarModule // <---- this module will include the code that must only run on the browser
 ],
 bootstrap: [AppComponent]

})
export class AppBrowserModule { }

Now I do not know which other files I should amend in order to make:

  • app.module.ts only platform agnostic code (shared module that can be imported to both server/browser modules)
  • server.module.ts only server side code (that can be ssr'ed)
  • browser.module.ts that include all the platform agnostic code and browser code (e.g. fullcalendar module
luk
  • 205
  • 3
  • 14
  • Does this answer your question? [Angular Universal npm run serve:ssr returns "document is not defined"](https://stackoverflow.com/questions/58420285/angular-universal-npm-run-servessr-returns-document-is-not-defined) – Nadhir Falta Mar 08 '21 at 17:33
  • Thank you this is not answering my question. The issue is the same but the way use isPlatform/isBrowser to resolve is incorrect (as mentioned in the link I provided from Angular github). I'm asking for support to setup third browser module which will have all code with browser api's like document/navigation/window etc – luk Mar 08 '21 at 20:00

1 Answers1

2

I overcomplicated things. In order to avoid browser api's being used on the server side, I simply wrapped the FullCalendar component in the ng-template like this:

in the constructer set isBrowser to isPlatformBrowser

 constructor(
   @Inject(PLATFORM_ID) private platformId,
   private eventService: EventsService, 
   private router: Router){
     this.isBrowser = isPlatformBrowser(this.platformId);
     console.log(this.isBrowser)
  }

and in the template:

<ng-container *ngIf="isBrowser">
    <full-calendar [options]="calendarOptions"></full-calendar>
 </ng-container>
luk
  • 205
  • 3
  • 14