1

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 class="col">
        <div class="row">
          <div class="col">{{aStringTitle}}</div>
        </div>
        <div class="row">
          <div class="col mt-2">
            {{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.

Batajus
  • 5,831
  • 3
  • 25
  • 38
Niteesh Bhargava
  • 157
  • 1
  • 10

1 Answers1

4

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 class="col">
    <div class="row">
      <div class="col">{{ entry.name }}</div>
    </div>
    <div class="row">
      <div class="col mt-2">
        <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.

Batajus
  • 5,831
  • 3
  • 25
  • 38
  • Thank you, I could not understand, angular website needs to have some basic examples, like React.js, Initially I could not understand what is injector: myInjector; and injector.create – Niteesh Bhargava Jan 03 '22 at 09:35