Create dynamic custom components and add it to an array


I want create by code a new instance of a custom component, change somethings and add it to an array. I want fill the array with different custom components.


myarray= [];

let a = new acomponent; = 'bla';

let b = new bcomponent;
b.blub = 'blubber';

let a = new acomponent; = 'blabla';

let d = new dcomponent;
d.hello = 'yo';

and so on

Afterwarts I would use it with *ngfor to fill a div.

Thanks in advance and best regards, anna-liebt.

Don’t think in terms of components in controllers; think only in terms of data model there, and leave the components to the template. I think you might see something along the lines of what you are trying to do in here.

I would do it conceptually the same way as what @rapropos linked. Say you have component1 through component5. Then you also create componentSelector, a component that has the other 5 components in its template, but only shows the correct component to the user, using something like ngIf or ngSwitch.

<componentSelector [componentData]="data" [componentType]="type"></componentSelector>
To make use of AOT compiling, you should know how many components there are ahead of time, and what they are. So I’d create an enum ComponentType indexing those 5 components, and that would be the variable type I would pass to component Selector. If your data structures are discordant, you could even have five input fields, component1Data through component5Data, and you only use the data field appropriate for the component type.

1 Like

Thanks rapropos and Aaron,

great Idea and something I could use for somethings I have in mind.

In this case, if it is possible I would prefer a solution like the pseudo code (if possible), because then I have a higher flexibility filling and extending the div, setting my settings and transfering existing c#-code for creating the different structures (and there are many) and settings inside the div.

By the way, great help you both provide.

Thanks, anna-liebt

I don’t see how that is consistent with AOT compiling. If you’re providing the components at runtime, that by definition is not ahead of time.

“Impossible” is quite a high bar, but what you are suggesting is highly unidiomatic for Angular apps, actively and strenuously discouraged by the framework authors, and even if achieved will result in a maintenance nightmare.


for that suggestions. Maybe I need to rethink some things. It would be so seductive about the existing code base. Ionic, angular and web things are very different to that things I have done before.

At the moment I am not able to implement swipe in a correct manner. What a shame.

Best regards, anna-liebt