0

I have objects of different types. Nevertheless, I want to display all types in one Angular2 component of mine. Here's the code I use for that:

in for-loop:
<div [ngSwitch]="Type">
    <c-test *ngSwitchCase="'Test'"></c-test>
    <c-test2 *ngSwitchCase="'Test2'"></c-test2>
    <etc>
</div>

Over time, my application could expand, adding new "types" of objects. Since I use the kind of code above in different places, I do not want to add a line in all of these places for each added type. Is there a way of using something similar to the C++ precompiler that will go over my folder-structure and add these lines accordingly?

Example: Let's say I have the following folder-structure.

Objects
|- TypeA
|- TypeB
|- etc

In my code, I will then have something like this:

<div [ngSwitch]="Type">
    <precompile *ngFor="some looping through folders">    
        <"c-$FoundFolder" *ngSwitchCase="'$FoundFolder'"><"c-$FoundFolder">
    </precompile>
</div>

Resulting in:

<div [ngSwitch]="Type">
    <c-TypeA *ngSwitchCase="'TypeA'"></c-TypeA>
    <c-TypeB *ngSwitchCase="'TypeB'"></c-TypeB>
    <etc *ngSwitchCase="'etc'"></c-etc>
</div>

I know that what I want does not exist in this form, but is there a way of achieving something similar, and if yes, how so?

user2065501
  • 99
  • 2
  • 9

1 Answers1

1

The below approach doesn't work exactly as per your requirement. But, the basic intend is to load a new component dynamically in future without changing the rendering view, based on new component added to the application. There is a nice article on angular website on this:

https://angular.io/docs/ts/latest/cookbook/dynamic-component-loader.html

Just that, it will remain same for the new declaration of component, just you need to make an additional entry in entryComponent for each new component added in the same module file where the new component is declared:

entryComponents: [ HeroJobAdComponent, HeroProfileComponent ],

Lambo14
  • 231
  • 1
  • 6
  • Thank you very much, this seems to be very close to what I wanted to do! I'll try it out and comment on how it goes. – user2065501 May 15 '17 at 17:29
  • There's a small problem I have with this method. In the documentation, they use a function returning all possible components with their data. However, I'd like to load a component by knowing the name only (Or something similar). Basically, to take the example of the documentation: Instead of ``, where ads is already loaded, I'd like to do: ``, where MyAdType is a string or file or whatever that will be used to load the component by add-banner. Is that possible? – user2065501 May 17 '17 at 12:55
  • Can you please create a sample plunker and explain me what you want to achive. May be then I will be able to help you. Thanks! – Lambo14 May 17 '17 at 19:13