0

I need some advice. I'm developing a dashboard in Angular2. My project can have different types and I want to display a component relating to each of these types.

This is how I do for now:

<div *ngIf="project.types.type1">
   <app-type1></app-type1>
</div>
<div *ngIf="project.types.type2">
   <app-type2></app-type2>
</div>
<div *ngIf="project.types.type3">
   <app-type3></app-type3>
</div>

But I would like to know if it's possible to write it in a more elegant way that could look this:

   <div *ngFor="let key of project.types | keys">
       <template name="app-{{key}}></template>
    </div>

Thanks

Julien Deruere
  • 770
  • 1
  • 7
  • 11
  • 2
    you may use different Routes to load different components in the `router-outlet` based upon your project type, did you give a thought on that? – Madhu Ranjan Dec 02 '16 at 19:41
  • What is the content of these components (`app-type1`, `app-type2`...)? If it is just template then you can use `ngTemplateOutlet` or `ngForTemplate` like here http://stackoverflow.com/questions/39974126/how-to-pass-an-expression-to-a-component-as-an-input-in-angular2/39977298#39977298 – yurzui Dec 02 '16 at 19:55
  • @MadhuRanjan my project can have many types. Each type can be display as a component, e.g.: if my project has type1, I will include the app-type1 component, and if it also has type2, I will include app-type1 AND app-type2 inside the view. – Julien Deruere Dec 02 '16 at 20:13
  • In that case you may load components dynamically using Component Factory, you will have to make a dictionary of app-type and selector though. – Madhu Ranjan Dec 02 '16 at 20:19
  • See also https://medium.com/@DenysVuika/dynamic-content-in-angular-2-3c85023d9c36#.5x153dypu – yurzui Dec 02 '16 at 20:35

1 Answers1

0

This isn't the looping solution you were looking for but its still a slight improvement in elegance from how you are currently doing it (in my opinion)

<div [ngSwitch]="project.types">

  <app-type1 [*ngSwitchCase]="project.types.type1"></app-type-1>
  <app-type2 [*ngSwitchCase]="project.types.type2"></app-type-2>
  <app-type3 [*ngSwitchCase]="project.types.type3"></app-type-3>

</div>
Kevin Aud
  • 378
  • 2
  • 12