0

I have array of components stored in main component. They are of different types. I used ngFor and ngSwitch directives to display them all.

<div *ngFor="let component of components"
         [ngSwitch]="component.id">
        <component-a *ngSwitchCase="1"></component-a>
        <component-b *ngSwitchCase="2"></component-b>
        <component-c *ngSwitchCase="3"></component-c>
</div>

This approach is quite problematic when I add new type, e.g. ComponentX, beacuse I have to add another ngSwitch case. Is there any possibility to make it more generic?

mankers
  • 742
  • 10
  • 19

1 Answers1

0

I have 3 solutions depending on what it is that you'r trying to achieve.

  1. Drop the ngSwitch statements and wrap the template of each component in an *ngIf statement. You'll have to create a service to house an observable of the data used to determine which will be show (i.e. the logic used in your swicth statement). you'll then inject that data into each.
  2. The angular router is also an option.
  3. (I suspect this is the best solution) Depending on how long your list of components is, you could just list them all and add an *ngIf to each and keep the logic on the component.

Is the order of the components in the array important at all? Also, how many components are there?

Nate May
  • 3,814
  • 7
  • 33
  • 86