how can I inject a component inside a loop

41 Views Asked by At

we can inject an Angular component dynamically ViewContainerRef.createComponent() where ViewContainerRef refers to a template reference like this <ng-template #ref>

how can we achieve the same approach, but when the template reference is created inside a loop, like this

@for(item of items; track item){
  <div>
   <!-- some nested markups -->

   <!-- inject each item's component here -->
   <!-- this should be created several times, once for each item -->
   <ng-template #ref></ng-template> 
 </div>
}
items = [
  component1,
  component2
]
1

There are 1 best solutions below

0
Martin Araujo On

You can use ngComponentOutlet. https://angular.io/api/common/NgComponentOutlet

Example:

@for (component of components; track $index) {
    <ng-container *ngComponentOutlet="component"></ng-container>
}