0
votes

I am trying to load components dynamically from the response of an API Call.

Lets say I have 3 components/widgets A, B and C. Depending on the response of the API call, I have to load either A, B, C or any combination of them in any order (like load them in the order of C and then B). Somewhat like a CMS on the client side.

The one solution I thought of was using getting HTML code with ids of components from the API and using [innerHtml].

Are there any alternative solutions where I can get a list of widget/component from API, and load them in Angular Dynamically?

2

2 Answers

1
votes

I thought of was using getting HTML code with ids of components from the API and using [innerHtml]

Why don't you use content-projection for such things instead of creating multiple component. Create one component and pass the html using ng-content in the child component. You can check here for more details.

here any alternative solutions where I can get a list of widget/component from API, and load them in Angular Dynamically?

You can use ComponentFactoryResolver from angular which will help you to get it done. You need to get viewContainerRef and using the ComponentFactoryResolver create a component dynamically and inject it.

This is a good reference you can follow to do it.

0
votes

There is a concept called "ComponentFactoryResolver". Hope this will help you on your case.

For more details: https://angular.io/guide/dynamic-component-loader#resolving-components