0
votes

Basically, I have a parent component named "Pageview" that shows several examples of how a specific component can be used. The current component displayed should change via a route input property received by the Pageview component. Ultimately, I want to be able to display multiple versions of that component at once and pass them different input properties (to show examples of how that component can be used).

In Vue, you can do something easy like:

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

I know there some stuff on Dynamic Components in the Angular docs, but it really only easily applies to making a single dynamic component and then passing it its Input properties within the parent component .ts file (through ViewChild, ViewContainerRef, Component Factory Resolver, etc...). However, I am trying to make multiple of the same child component, each with different input properties.

The angular docs currently recommend something like:

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

Where currentComponent is a directive containing a ViewContainerRef. I Would then be able to create a component Instance within the parent.

However, how do I extend this to adding an *ngFor to create multiple of the components, and then also get each to have their unique Input properties (like in the Vue example).

1
It may help to add a code sample so we can get a better idea of what you're trying to do.Ashley

1 Answers

0
votes

You can create dynamic components using a for loop also. One of the ways i solved is passing the different components as input ( the components can be same ).

Please refer example below

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

To send the components you can simply pass the components like this :-

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

Above code uses Generics, so any data can be used by the dynamic components. Hope this helps.

Complete code can be found here

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