【问题标题】:Dynamic component rendering based on parent input property?基于父输入属性的动态组件渲染?
【发布时间】:2019-11-21 16:17:40
【问题描述】:

基本上,我有一个名为“Pageview”的父组件,它展示了如何使用特定组件的几个示例。当前显示的组件应通过 Pageview 组件接收的路由输入属性进行更改。最终,我希望能够一次显示该组件的多个版本并向它们传递不同的输入属性(以展示如何使用该组件的示例)。

在 Vue 中,你可以做一些简单的事情,比如:

<component
  :is = "currentComponent"
  v-for: "example in examplesOfCurrentComponent"
  :text: "example.text"
 > 
<div v-if="example.slotContent" v-html="example.slotContent" />
</component

我知道 Angular 文档中有一些关于动态组件的内容,但它实际上只适用于制作单个动态组件,然后在父组件 .ts 文件中传递其输入属性(通过 ViewChild、ViewContainerRef、组件工厂解析器等...)。但是,我正在尝试制作多个相同的子组件,每个子组件具有不同的输入属性。

角度文档目前推荐如下内容:

    <ng-template currentComponent
    ></ng-template>

其中 currentComponent 是一个包含 ViewContainerRef 的指令。然后我就可以在父级中创建一个组件实例。

但是,我如何将其扩展为添加 *ngFor 以创建多个组件,然后还让每个组件都有其独特的 Input 属性(如 Vue 示例中)。

【问题讨论】:

  • 添加代码示例可能会有所帮助,以便我们更好地了解您要执行的操作。

标签: angular


【解决方案1】:

您也可以使用 for 循环创建动态组件。我解决的一种方法是将不同的组件作为输入传递(组件可以相同)。

请参考以下示例

this.components.forEach( (sideNavComponent: DrawerConfig) => {
  const factory = this.resolver.resolveComponentFactory(sideNavComponent.type);
  const componentRef = this.vc.createComponent(factory);
  const component = componentRef.instance;
  component.data = sideNavComponent.data;
});

https://github.com/sanketmaru/ng-lib-sank/blob/master/projects/ng-lib-sank/src/lib/drawer/drawer.component.ts#L29

要发送组件,您可以像这样简单地传递组件:-

public components: [DrawerConfig<DrawerItemComponent>, DrawerConfig<DrawerItemComponent>] = [
    {
      type: DrawerItemComponent,
      data: {
        name: 'First Component'
      }
    },
    {
      type: DrawerItemComponent,
      data: {
        name: 'Second Component'
      }
    }
  ];

以上代码使用泛型,因此动态组件可以使用任何数据。希望这可以帮助。

完整的代码可以在这里找到

https://github.com/sanketmaru/ng-lib-sank/blob/master/src/app/app.component.ts#L17

【讨论】:

  • 还有一个问题——如何将innerHTML 添加到父组件中的子(动态)组件实例?例如,每个子组件都有 ng-content 标签,如上,我将如何放置“
    ”跨度>
猜你喜欢
  • 2017-02-03
  • 1970-01-01
  • 2018-12-21
  • 1970-01-01
  • 2019-11-26
  • 2011-07-17
  • 1970-01-01
  • 1970-01-01
  • 2018-11-12
相关资源
最近更新 更多