Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need BrowserAnimationsModule in Angular but gives error in Universal

Hi I am using Angular that uses the BrowserAnimationsModule. But in the universal server side it gives the error "document is not defined".

Because Universal doesn't support BrowserAnimationsModule I need a way to make the server ignore BrowserAnimationsModule and replace it with NoopAnimationsModule.

This is what I have right now but it's not working. Any other methods are welcome too.

let imports = [
    BrowserModule.withServerTransition({appId: 'ang4-seo'}),
    FormsModule,
    HttpModule,
    routes
];

if(isPlatformBrowser(PLATFORM_ID)){
    imports.push(BrowserAnimationsModule);
}

@NgModule({
    imports: imports,

Are there any ways to solve this?

like image 599
Raymond the Developer Avatar asked Jun 02 '17 13:06

Raymond the Developer


1 Answers

Edit: this solution doesn’t appear to work as of version 6.1. I’ll leave the below solution in case it works again someday and update if I find another solution.

Original answer:

I was having this exact same problem. Full credit goes to this fork on github from pquarme.

What you need to do is:

1) Remove any reference to BrowserAnimationsModule from app.module.ts and create a separate app.browser.module.ts file which contains:

import { NgModule } from '@angular/core';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

import { AppModule} from './app.module';
import { AppComponent } from './app.component';

@NgModule({
  imports: [
    BrowserAnimationsModule,
    AppModule
  ],
  bootstrap: [AppComponent]
})
export class AppBrowserModule { }

Basically your app.module.ts file will now be platform agnostic. Then, you'll have separate files for your app, your browser environment and your server environment.

2) Import NoopAnimationsModule to your app.server.module.ts so you don't throw errors in Node.

3) Modify your main.ts file to bootstrap AppBrowserModule instead of AppModule

After about 2 hours of searching, this was the only solution that worked for me.

like image 111
jafaircl Avatar answered Oct 20 '22 11:10

jafaircl