如何将 BrowserAnimationsModule 或 NoopAnimationsModule 添加到独立组件?

How to add BrowserAnimationsModule or NoopAnimationsModule to Standalone Component?

问题

当我将 BrowserAnimationsModuleNoopAnimationsModule 添加到独立 AppComponent 的导入数组时,它会破坏应用程序。

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

这些是我在添加其中任何错误时遇到的错误:

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.

当我不添加它时,我得到这个错误:

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).

到目前为止我的发现...

显然 BrowserAnimationsModuleNoopAnimationsModule 包含 BrowserModule,我猜独立组件也是如此。如何从动画模块或我的独立组件中排除 Browsermodule?或者是否有其他一些动画模块或解决方案可以帮助我解决这个问题?

如果您想亲自查看并尝试,这里有一个 Stackblitz

importProvidersFrom 函数提供了回到 NgModule 世界的桥梁。它不应该在组件提供中使用,因为它只能在应用程序注入器中使用

添加 importProvidersFrom 函数以在 main.ts 内提供 BrowserAnimationModule。

main.ts

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

Forked Example