将组件作为变量传递给 ngx-bootstrap 模态服务时类型不匹配

问题描述 投票:0回答:1

我正在按照here的示例从组件创建 ngx-bootstrap 模式。

但是,如果我使用三元运算符为组件创建一个变量,如果我不单独声明变量并对其进行赋值,则会出现奇怪的编译器错误。

换句话说,这是有效的:

let modal;
modal = someParameter ? FooComponent : BarComponent;
this.bsModalRef = this.bsModalService.show(modal);

(请注意,

FooComponent
BarComponent
都扩展了一个公共基类。)

但是如果我尝试这个:

let modal = someParameter ? FooComponent : BarComponent;
this.bsModalRef = this.bsModalService.show(modal);

我收到一个编译时错误,例如:

TS2345: Argument of type 'typeof FooComponent | typeof BarComponent' is not
assignable to parameter of type 'string | TemplateRef<any> |
(new (...args: any[]) => BarComponent)'.

Type 'typeof BarComponent' is not assignable to type 'string | TemplateRef<any> |
(new (...args: any[]) => FooComponent)'.

Types of construct signatures are incompatible.

接下来还有一些额外的抱怨,即这两个子类不共享相同的属性。

似乎发生的情况是,编译器随机选择一个类或另一个类作为要测试的类型签名,而不是遵循它似乎在错误消息的初始部分中识别的

|
。但我不明白为什么,或者为什么将声明与赋值分开会使问题消失。

欢迎任何意见。

angular typescript ngx-bootstrap
1个回答
0
投票

您可以为每个组件使用多个

this.modalService.open()
,但这似乎是解决问题的低效方法,因此我建议您将类型转换为其中一个组件,这将解决您的问题!

注意此类型仅用于打开模态框,它不会干扰模态组件中其他任何地方的输入!

this.bsModalRef = this.modalService.show(
  (this.test
    ? ModalContentComponent
    : ModalContentTwoComponent) as typeof ModalContentComponent
);

堆栈闪电战

© www.soinside.com 2019 - 2024. All rights reserved.