javascriptangularangular-dynamic-components

How can I render dynamic components in multidimensional array


I have a multidimensional array of components I want to render to a grid:

[
  [
    {
      component: class TitleComponent,
      data: {
        title: "Invoice"
      },
      row: 1
    },
    {
      component: class AddressComponent,
      data: {
        companyName: "Comapny Name",
        addressLineOne: "123 Street Name",
        addressLineTwo: "Area",
        addressLineThree: "City"
      },
      row: 1
    }
  ],
  [
    {
      component: class DetailsComponent,
      data: {
        description: "lorem ipsum dolor sit amet"
      },
      row: 2
    }
  ]
]

I want to render the component in the required row, for example, the TitleComponent should be rendered in the first row, while the DetailsComponent should be rendered in the second row.

The html structure I am looking to output is something like this:

<div *ngFor="let row of rows">
  <div *ngFor="let component of row">
    <ng-template gridBlock></ng-template>
  </div>
</div>

Not sure how possible the output is, but essentially I want to create a row for each array and then render each component inside the relevant row.

I have used @ViewChildren to render the components, but seems like whenever I add a new dynamic component to the Querylist, it messes up the order in which the components are rendered.

@ViewChildren( GridContainerDirective ) components!: QueryList< GridContainerDirective >

P.S. I am new to angular and any help or direction will be much appreciated.


Solution

  • you can render components with the help of *ngComponentOutlet directive

    <div *ngFor="let row of rows">
      <div *ngFor="let component of row">
        <ng-container *ngComponentOutlet="component.component"></ng-container>
      </div>
    </div>
    

    however it is not possible to pass data directly. so it would be required to craete injectors for those components, and inject the data inside of them