angularangular14

How to add BrowserAnimationsModule or NoopAnimationsModule to Standalone Component?


When I add either a BrowserAnimationsModule or a NoopAnimationsModule to the imports array of my Standalone AppComponent, it breaks the application.

@Component({
  standalone: true,
  imports: [
    CommonModule,
    NoopAnimationsModule,
    /* ... */
  ],
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})

These are the errors I'm getting when I add any of them:

ERROR Error: Uncaught (in promise): Error: Providers from the `BrowserModule` have already been loaded.
If you need access to common directives such as NgIf and NgFor, import the `CommonModule` instead.

Error: Providers from the `BrowserModule` have already been loaded.
If you need access to common directives such as NgIf and NgFor, import the `CommonModule` instead.

And when I don't add it, I get this error:

ERROR Error: Unexpected synthetic property @transitionMessages found. Please make sure that:
 - Either `BrowserAnimationsModule` or `NoopAnimationsModule` are imported in your application.
 - There is corresponding configuration for the animation named `@transitionMessages` defined in
 the `animations` field of the `@Component` decorator (see
 https://angular.io/api/core/Component#animations).

Solution

  • The importProvidersFrom function provides a bridge back to the NgModule world. It should not be used in component provide as it is only usable in an application injector

    Add importProvidersFrom function to provide BrowserAnimationModule inside main.ts.

    main.ts

    bootstrapApplication(AppComponent,{
      providers:[importProvidersFrom([BrowserAnimationsModule])]
    }); 
    

    Forked Example

    Update Angular 14+

    Angular new versions provide two new function provideAnimations() and provideNoopAnimations() to enable and disable animation. we could use it like this.

        import { provideAnimations } from '@angular/platform-browser/animations';
    
        bootstrapApplication(AppComponent, {
            providers: [
              provideAnimations()
            ]
         })
    

    Documentation Link