无法在ngx-bootstrap模态框中传递ModalOptions与class的问题求助
ngx-bootstrap模态框合并配置项类型错误的解决办法
问题场景
我正在使用ngx-bootstrap模态框,现有代码如下:
const modalRef = this.modalService.show<ListComponent>(ListComponent); modalRef.content.selecteduse.subscribe((x) => { this.func1(); });
同时定义了ModalOptions配置项:
modOpt: ModalOptions = { backdrop: 'static', keyboard: false, ariaLabelledBy: 'modal-basic-title', ignoreBackdropClick: true, id: 1, }
尝试将class与modOpt合并传入show方法:
const modalRef = this.modalService.show<ListComponent>(ListComponent,{ class: 'modal-dialog create_modal_new', ...this.modOpt });
但出现如下类型错误:
Argument of type '{ id?: number; backdrop?: boolean | "static";
keyboard?: boolean; focus?: boolean; show?: boolean;
ignoreBackdropClick?: boolean; class: string; animated?: boolean;
initialState?: Partial; providers?: StaticProvider[];
ariaLabelledBy?: string; ariaDescribedby?: string; }' is not
assignable to parameter of type 'ModalOptions'
解决办法
1. 类型断言快速修复
直接通过类型断言告知TypeScript合并后的对象符合ModalOptions类型,快速绕过类型检查:
const modalRef = this.modalService.show<ListComponent>( ListComponent, { class: 'modal-dialog create_modal_new', ...this.modOpt } as ModalOptions );
2. 扩展自定义类型(推荐)
如果需要长期使用自定义class配置,扩展官方ModalOptions类型让TypeScript识别class属性:
import { ModalOptions } from 'ngx-bootstrap/modal'; // 扩展ModalOptions,添加class属性 interface CustomModalOptions extends ModalOptions { class?: string; } // 修改配置项类型为自定义类型 modOpt: CustomModalOptions = { backdrop: 'static', keyboard: false, ariaLabelledBy: 'modal-basic-title', ignoreBackdropClick: true, id: 1, } // 合并配置时不再报错 const modalRef = this.modalService.show<ListComponent>( ListComponent, { class: 'modal-dialog create_modal_new', ...this.modOpt } );
3. 升级ngx-bootstrap版本
部分旧版本的ModalOptions类型定义未包含class属性,升级到最新稳定版即可解决:
npm install ngx-bootstrap@latest --save
升级后原合并代码可直接正常使用,无需额外修改。
内容的提问来源于stack exchange,提问作者user3653474
相关产品推荐
相关产品推荐

