You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 7自定义Toastr组件不生效且报@flyInOut动画模块错误

让我帮你梳理下可能遗漏的配置点,你已经做了基础工作,但还有几个关键细节容易忽略:

1. 确认BrowserAnimationsModule的导入顺序与位置

虽然你提到已引入动画模块,但要确保它在ToastrModule之前导入,且位于AppModule的imports数组中——Toastr的动画依赖这个模块,顺序不对会导致识别失败。示例配置:

import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { ToastrModule } from 'ngx-toastr';
import { CustomToastComponent } from './path/to/custom-toast.component';

@NgModule({
  imports: [
    BrowserAnimationsModule, // 必须放在ToastrModule前面
    ToastrModule.forRoot({
      toastComponent: CustomToastComponent, // 全局指定自定义组件
      // 其他Toastr配置(比如位置、时长等)
    }),
  ],
  declarations: [CustomToastComponent], // 务必声明自定义组件
  // Angular 9+ 无需entryComponents(Ivy编译器自动处理);若使用Angular 8及以下,才需要添加entryComponents: [CustomToastComponent]
})
export class AppModule { }

如果仍然报动画错误,可以临时替换为NoopAnimationsModule(禁用动画)排查:若替换后报错消失,说明可能是BrowserAnimationsModule与ngx-toastr版本不兼容,需要核对两者版本匹配性。

2. 自定义Toast组件必须正确处理动画触发器

报错中的@flyInOut是Toastr内置的动画触发器,你的自定义组件需要显式引入并绑定这个动画:

组件类示例

import { Component, Input } from '@angular/core';
import { Toast } from 'ngx-toastr';

@Component({
  selector: 'app-custom-toast',
  templateUrl: './custom-toast.component.html',
  styleUrls: ['./custom-toast.component.css'],
  animations: [Toast.flyInOut] // 必须导入Toastr的内置动画
})
export class CustomToastComponent extends Toast {
  @Input() message!: string;
  @Input() title!: string;
  // 可添加自定义逻辑或属性
}

模板示例(必须绑定动画状态)

<div [@flyInOut]="state" class="custom-toast-container">
  <h3>{{ title }}</h3>
  <p>{{ message }}</p>
  <!-- 自定义按钮或其他元素 -->
</div>

这里的state是继承自Toast类的内置属性,由Toastr自动管理动画状态,必须在模板中绑定才能触发动画,否则会报找不到@flyInOut的错误。

3. 验证全局配置是否生效,或显式指定自定义组件

如果全局配置的toastComponent未生效,可以在调用Toastr时显式指定组件,排查是否是全局配置的问题:

import { ToastrService } from 'ngx-toastr';
import { CustomToastComponent } from './path/to/custom-toast.component';

constructor(private toastr: ToastrService) {}

showCustomToast() {
  this.toastr.success('自定义提示内容', '自定义标题', {
    toastComponent: CustomToastComponent // 显式指定使用自定义组件
  });
}

4. 核对版本兼容性

ngx-toastr与Angular版本必须匹配,比如Angular 16需要对应ngx-toastr 17.x版本,版本不兼容会导致各种奇怪的配置失效问题。你可以查看package.json中的版本号,确保两者版本适配。

内容的提问来源于stack exchange,提问作者pedrodotnet

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 06:43:58