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

升级ngx-bootstrap 10后BsModalRef.content始终为undefined的问题

ngx-bootstrap 10 后 BsModalRef.content 为 undefined 的问题解决

问题原因

ngx-bootstrap 10 版本重构了模态框的初始化逻辑,BsModalService.show() 改为异步执行。原代码中调用 show() 后立即访问 bsModalRef.content,此时模态框组件还未完成初始化挂载,导致 content 属性返回 undefined。

另外需确认:传入的自定义模态框组件是否已在所属 Angular 模块的 declarations 数组中声明(Angular 9+ 启用 Ivy 后无需手动配置 entryComponents,但仍需确保组件被模块识别)。

修复方案

方案1:监听模态框显示完成事件(推荐)

通过 BsModalRef 的 onShown 事件回调,在组件完全初始化后再操作 content 属性:

displayModal(modalComponent: any, message: any, title: string, iconType: string, _modalSize: string) {
  // 原有尺寸判断逻辑保持不变
  let modalSize = '';
  if ((_modalSize === MapConstants.ModalSettings.ModalSmall) || (_modalSize === '') || (_modalSize === undefined)) {
    modalSize = 'modal-dialog-centered modal-sm';
  } else if (_modalSize === MapConstants.ModalSettings.ModalLarge) {
    modalSize = 'modal-lg modal-dialog-centered';
  } else if (_modalSize === MapConstants.ModalSettings.ModalMedium) {
    modalSize = 'modal-dialog-centered';
  }

  const initialState = {
    message: message,
    title: title,
    iconSize: 'xx-large',
    iconType: iconType,
    fontSize: 'x-large'
  };

  this.bsModalRef = this.modalService.show(modalComponent, Object.assign({
    class: modalSize,
    initialState
  }, this.config));

  // 等待模态框显示完成,组件初始化后再访问content
  const shownSubscription = this.bsModalRef.onShown.subscribe(() => {
    this.bsModalRef.content.closeBtnName = 'Close';
  });

  // 模态框关闭时取消订阅,避免内存泄漏
  this.bsModalRef.onHidden.subscribe(() => {
    shownSubscription.unsubscribe();
  });
}

方案2:确认组件的模块配置

如果使用的是自定义模态框组件,需确保其在所属模块中正确声明:

@NgModule({
  declarations: [YourCustomModalComponent],
  // Angular 8 及以下版本需添加到entryComponents
  // entryComponents: [YourCustomModalComponent]
})
export class YourFeatureModule {}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 08:10:24