angularangular-componentsdynamic-htmlangular-factory

Angular2 Partial Dynamic Component approach


I need to build a dynamic html page(content & order are generated in run time). I will generate angular 2 components according to server response(json).

I saw that i can take the ComponentFactoryResolver approach. it looks massy and little hacky.

Then i was thinking about the following idea:

dynamic.component.html:

<div *ngFor="let item of dynamicItems">
  <div [ngSwitch]="item.type">
    <template [ngSwitchCase]="component1">
       <component1 [data]="item.data"></component1>
    </template>
    <template [ngSwitchCase]="component2">
       <component2 [data]="item.data"></component2>
    </template>
    <template [ngSwitchCase]="component3">
       <component3 [data]="item.data"></component3>
    </template>¯
    <template [ngSwitchCase]="component4">
       <component4 [data]="item.data"></component4>
    </template>
  </div>
</div>

dynamicItems is array received from the server.

what are the implications of using this approach ? Is it bad practice ?


Solution

  • Felt this is good

    <div *ngFor="let item of dynamicItems">
     <component1 *ngIf="item.type=='component1'" [data]="item.data"></component1>
     <component2 *ngIf="item.type=='component2'" [data]="item.data"></component2>
     <component3 *ngIf="item.type=='component3'" [data]="item.data"></component3>
     <component4 *ngIf="item.type=='component4'" [data]="item.data"></component4>
    </div>