Home > front end >  Different types of components in same ngFor
Different types of components in same ngFor

Time:10-27

I'm getting an object from an API. It has an array which contains 2 types of objects, I have to loop over this array and render two different components depending on the object at each index.

Both types of components need @Inputs and @Outputs to work properly, so I can't use <ng-container> like showing in this question.

What's the best way to implement something like this?

CodePudding user response:

Your question needs more clarity. Can you include the code that has the errors?

CodePudding user response:

If you only have 2 components, then you could use something like this to check which component type to render:

<ng-container *ngFor="let item of items">
  <ng-container *ngTemplateOutlet="<type check condition here> ? type1 : type2; context: { $implicit: item }">
  </ng-container>
</ng-container>

<!-- in each one of these templates you can access the item in the array via "item" -->
<ng-template #type1 let-item>
  <!-- render component for type 1 here -->
</ng-template>

<ng-template #type2 let-item>
  <!-- render component for type 2 here -->
</ng-template>

You might want to look into ngSwitch as well if the number of component types increases in the future.

  • Related