Home > Net >  Pass angular components as array to html template
Pass angular components as array to html template

Time:01-03

Context :-Small Angular Application(only two tabs on single screen) deployed independently as static assets in AWS S3 bucket.

Given :- One of my Angular(12) container Component have long markup, but most of code is duplicated due to creating grid, I have few columns in a row like below

<div >
        <div >
          <div >{{aStringTitle}}</div>
        </div>
        <div >
          <div >
            {{differentMarkupForEachColumn}}
          </div>
        </div>
      </div>

What I want to achieve :- I want to render these columns using *ngFor passing array of following type :-

    [
      {name: 'First Ng Component', component: <SmallAngularComponent>},
      {name: 'Second Ng Component', component: <AnotherSmallAngularComponent>},
      ...... and so on upto 7-8 smaller angular components    
    ]

When I checked angular.io I could not find suitable example in template docs.

Actual question :- How to pass an array of Angular components to the template of a containing Angular component ?

What I don't want :- Alternative approach is explained in this answer, but I want to render proper Angular components and not some random html.

CodePudding user response:

So, if I understood you correctly, you want to dynamically create these components in your HTML.

To do so you can simply use the NgComponentOutlet (see here for more).

Your code would look like following:

component.ts

components = [
  { name: 'First Ng Component', component: SmallAngularComponent },
  { name: 'Second Ng Component', component: AnotherSmallAngularComponent },
  // ...... and so on upto 7-8 smaller angular components    
];

You might have noticed that you don't need <>for the components.

component.html

<ng-container *ngFor="let entry of components">
  <div >
    <div >
      <div >{{ entry.name }}</div>
    </div>
    <div >
      <div >
        <ng-container *ngComponentOutlet="entry.component"></ng-container>
      </div>
    </div>
  </div>
</ng-container>

If you need to pass params to the different components you can have a look here or you need to programmatically create these components.

  • Related