0
votes

I was wondering if there's a way in angular, where one can generate components at run time, from a general template?

For example, if I have a dashboard of widgets, where a backend server tells me how many widgets are rendered, is there a way to create a component for each of the widgets and add them as child to the parent dashboard component?

This might not even be the best way to do this, but for curiosity's sake I was wondering if it was possible, and if it is, whether it is a good practice.

I've looked at dynamic components in angular, but there you've a predefined component (like a modal) which you can load/unload at runtime.

Edit: I could use ngFor/ngIf constructs if I need to display the widgets, the reason I'd want components is that I'd like to do a bunch of other tasks, like setup observables based on which widget it is.

1

1 Answers

0
votes

Well, the easiest solution would be to have some fixed widgets and just render them using data from your backend and *ngFor and *ngIf even tho that's not exactly a beautiful solution.

<div class='dashboard'>
    <ng-content *ngFor='let widget of widgets'>
        <ng-content *ngIf='widget.type == 1'><app-widget1></app-widget1></ng-content>
        ....
    </ng-content>
</div>

There's also the ComponentFactoryResolver which can be used to load components dynamicaly at runtime as described here. Haven't tried myself so I can not provide an example but there is example code on the guide and maybe it fits your needs.