繁体   English   中英

尝试将组件名称从字符串转换为 angular 9 中的组件类型会给出传入的类型不是 ComponentType 错误

[英]Trying to convert a Component name from string to Component type in angular 9 gives Type passed in is not ComponentType error

在模板 HTML 中:

<ng-container *ngComponentOutlet="getComponent(item.component); injector: dynamicComponentInjector">
</ng-container>

In.ts 文件(这工作)

getComponent(component){
    return component; //component = 'ProductTitleComponent'
}

但是(这不起作用)因为我从数据库中获取值,所以我将它作为字符串获取,例如“ProductTitleComponent”。 我尝试了以下选项,但没有任何反应。

出现错误:错误:断言错误:传入的类型不是 ComponentType,它没有“ɵcmp”属性。

getComponent(component){
  return component as Component; //component = 'ProductTitleComponent'
}


getComponent(component){
  return JSON.parse(component); //component = 'ProductTitleComponent'
}

我能够通过这样做来解决问题

getComponent(component){
  const comp = { ProductTitleComponent }
  return comp[component];
}

将“ProductTitleComponent”视为组件值。 在这种情况下,我必须在每次创建一个组件来组合 object时添加一个组件。 有没有更好的解决方案。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM