in my angular application i am dealing with a lot of component that dynamically rendered in run time, but i must specify the component before compiling to inject it in the run time, is there is away to load component by it's name as string ...
say ... i have two component FirstComponent
And SecondComponent
can i store the name of them in an array and them by user action decide which component to be rendered, and it don't want to use if condition on the name or something like this. i want something run generic with it's own in case i change the array or add new component to the array i don't want to change the code wrote.
Thanks A Lot In Advance...
And i am using ng-dynamic-component
for adding dynamic component to the page,
if there is a way does this library implement it.
Asked
Active
Viewed 530 times
0

Hassan Ahmed
- 73
- 4
- 10
-
Can you share a code sample you are working on (StackBlitz) – DevLoverUmar Nov 12 '19 at 13:45
1 Answers
0
You can use ViewContainerRef.
It is well explained int his tutorial.
https://medium.com/front-end-weekly/dynamically-add-components-to-the-dom-with-angular-71b0cb535286
classNames.forEach(type=> {
const factory = this.resolver.resolveComponentFactory(type);
const compRef = this.vcRef.createComponent(factory);
});
- vcRef refers to object of ViewContainerRef.
- resolver refers to ComponentFactoryResolver

Saloo
- 816
- 6
- 13
-
the resolver can't accept name as string it says `Argument of type '"TestComponent"' is not assignable to parameter of type 'Type
'.` – Hassan Ahmed Nov 12 '19 at 14:38 -
@HassanAhmed I think you can create type from string using this method and then pass to resolveComponentFactory https://stackoverflow.com/questions/15338610/dynamically-loading-a-typescript-class-reflection-for-typescript – Saloo Nov 12 '19 at 14:58