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

Angular 7升级ng-bootstrap至4.0.0后模态框报错咨询

搞定ng-bootstrap升级4.0.0后模态框的组件工厂错误

嘿,我知道升级组件遇到这种报错有多闹心!你遇到的Error: No component factory found for [object Object]. Did you add it to @NgModule.entryComponents?问题,还有Stackblitz里找不到包的情况,我帮你梳理清楚原因和解决办法:

一、先搞懂为啥会报错

这个错误主要和两个核心点有关:

  1. 版本不兼容:ng-bootstrap 4.0.0只适配Angular 8.x版本,如果你的项目Angular版本低于8或者高于8(比如9+),直接升级肯定出兼容性问题;
  2. 组件注册逻辑变了:ng-bootstrap 3.x之后,模态框的注册方式改了——Angular 9+甚至不需要entryComponents配置了,但如果你的代码还沿用旧写法,或者模块配置有误,就会触发这个找不到组件工厂的错误。

二、一步步解决问题

1. 先把版本配对应

先查下你的Angular版本,再对应安装合适的ng-bootstrap:

  • 要是用Angular 8.x → 装ng-bootstrap 4.0.0就行
  • 要是Angular 9及以上 → 直接装ng-bootstrap 5.x或更高版本(因为4.x和Angular 9+的Ivy编译器不兼容)

执行对应的安装命令:

# Angular 8.x装4.0.0版本
npm install @ng-bootstrap/ng-bootstrap@4.0.0 --save

# Angular 9+装最新兼容版
npm install @ng-bootstrap/ng-bootstrap@latest --save

2. 修正模态框的注册和调用

ng-bootstrap 4.x里,模态框组件必须在所属模块的declarations里声明(Angular 9+不用加entryComponents了),而且调用的时候要传组件类,不是对象!

模块配置示例:

import { NgModule } from '@angular/core';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { YourModalComponent } from './your-modal.component';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent,
    YourModalComponent // 一定要把模态框组件放在这里!
  ],
  imports: [
    NgbModule // 别忘导入ng-bootstrap模块
  ],
  // Angular 8及以下如果还需要的话加这个,Angular 9+直接删掉
  // entryComponents: [YourModalComponent]
})
export class AppModule { }

组件里调用模态框的正确姿势:

import { Component } from '@angular/core';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { YourModalComponent } from './your-modal.component';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent {
  constructor(private modalService: NgbModal) { }

  openTestModal() {
    // 这里要传组件类YourModalComponent,不是对象!
    const modalRef = this.modalService.open(YourModalComponent);
    // 要传数据的话,用componentInstance就行
    modalRef.componentInstance.modalData = '你要传给模态框的数据';
  }
}

3. 解决Stackblitz找不到包的问题

Stackblitz里搜不到包,大概率是手动改package.json的版本号不对,或者包源没同步:

  • 别手动改package.json了,直接在Stackblitz的「Dependencies」面板里搜索@ng-bootstrap/ng-bootstrap,选对应版本添加就行;
  • 如果已经手动改了,刷新下页面,Stackblitz会自动重新安装依赖。

三、最后再提醒几个小细节

  • 升级ng-bootstrap的时候,记得把@angular/core和@angular/common也更到对应的兼容版本,不然还是会有奇怪的问题;
  • 要是用Angular 9+的Ivy编译器,别让Tree Shaking把模态框组件给摇没了,确保组件在模块里显式声明;
  • 检查下代码里有没有旧写法——比如之前可能传的是new YourModalComponent()这种对象,现在必须传组件类。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 11:02:58