【问题标题】:How to add generic component in angular 8如何在 Angular 8 中添加通用组件
【发布时间】:2023-03-23 14:51:01
【问题描述】:

在我的角度应用程序中,我正在处理许多在运行时动态呈现的组件,但我必须在编译之前指定组件以在运行时注入它,是否可以通过其名称作为字符串加载组件... 说...我有两个组件 FirstComponentSecondComponent 我可以将它们的名称存储在一个数组中,它们通过用户操作决定要呈现哪个组件,并且它不想在名称上使用 if 条件或类似的东西。我想要一些通用的东西,以防我更改数组或向数组添加新组件,我不想更改编写的代码。 非常感谢提前... 我正在使用ng-dynamic-component 向页面添加动态组件, 如果这个库有办法实现它。

【问题讨论】:

  • 你能分享一个你正在研究的代码示例吗(StackBlitz)

标签: angular angular-directive angular-dynamic-components


【解决方案1】:

您可以使用 ViewContainerRef

在他的教程中有很好的解释。

https://medium.com/front-end-weekly/dynamically-add-components-to-the-dom-with-angular-71b0cb535286

    classNames.forEach(type=> {
           const factory = this.resolver.resolveComponentFactory(type);
           const compRef = this.vcRef.createComponent(factory);
             });
  • vcRef 引用 ViewContainerRef 的对象。
  • 解析器是指 ComponentFactoryResolver

【讨论】:

  • 解析器不能接受名称为字符串Argument of type '"TestComponent"' is not assignable to parameter of type 'Type<unknown>'.
  • @HassanAhmed 我认为您可以使用此方法从字符串创建类型,然后传递给 resolveComponentFactory stackoverflow.com/questions/15338610/…
猜你喜欢
  • 2020-01-18
  • 1970-01-01
  • 1970-01-01
  • 2020-03-21
  • 2020-06-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-04
相关资源
最近更新 更多