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

Angular项目使用NgbActiveModal关闭活跃模态框报NullInjectorError如何解决

问题解决方法

报错原因

NgbActiveModal 是 ng-bootstrap 模态框专属的依赖,仅会在被NgbModalService动态打开的模态框内容组件的上下文中自动提供,你当前的ModalComponent是用来触发模态框打开的父容器,不在模态框内容的注入上下文中,直接在构造函数注入自然找不到对应的provider,就会抛出NullInjectorError。

具体改造步骤

  • 第一步:移除构造函数中的NgbActiveModal注入声明
  • 第二步:存储modalService.open()返回的当前模态框实例,后续通过实例单独关闭对应模态框
  • 第三步:修改close方法,调用存储的实例方法关闭当前模态框,替换原有的dismissAll

修改后完整代码

import {Component, ElementRef, Input, ViewChild} from '@angular/core';
import {NgbModal, NgbModalRef} from '@ng-bootstrap/ng-bootstrap';
import {faTimes} from '@fortawesome/free-solid-svg-icons';

@Component({
    selector: 'app-modal',
    templateUrl: './modal.component.html',
    styleUrls: ['./modal.component.scss']
})
export class ModalComponent {
    @Input() titel: string = 'Editor';
    @Input() popupClass: string;
    @ViewChild('content') content: ElementRef;
    cross = faTimes;
    // 存储当前打开的模态框实例
    private currentModalRef?: NgbModalRef;

    constructor(private modalService: NgbModal) {
    }

    open() {
        this.currentModalRef = this.modalService.open(this.content,
        {   ariaLabelledBy: 'modal-basic-title',
                        windowClass: this.popupClass
                });
        // 处理返回结果逻辑不变
        this.currentModalRef.result.then((result) => {}, (reason) => {});
    }

    close() {
        // 仅关闭当前模态框实例,不影响其他打开的模态框
        this.currentModalRef?.dismiss();
    }
}

补充说明

如果后续你有单独封装的模态框内部内容组件,需要在内容组件内部触发关闭时,才需要在内容组件的构造函数中注入NgbActiveModal,调用它的dismiss()/close()方法关闭当前内容所属的模态框。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 01:36:00