Is there a way to dynamically create multiple instances of the same component in angular? I have tried it using componentFacory, but no success.
-
What problems did you run into? Can you provide any code showing how you did it?Daniel W Strimpel– Daniel W Strimpel2018-05-12 03:58:39 +00:00Commented May 12, 2018 at 3:58
-
I just created a simplified example on stackblitz and it actually worked. Must have done something wrong when trying it in our app. Anyway, if anyone wants to know how here it is: stackblitz.com/edit/angular-4aus6a.Yhlas– Yhlas2018-05-12 06:10:00 +00:00Commented May 12, 2018 at 6:10
Add a comment
|
1 Answer
private helloRef: ComponentRef<HelloComponent>;
private byeRef: ComponentRef<GoodbyeComponent>;
private helloCopyRef: ComponentRef<HelloComponent>;
@ViewChild('host', {read: ViewContainerRef}) theHost: ViewContainerRef;
constructor(private resolver: ComponentFactoryResolver, private injector: Injector) { }
ngOnInit(): void {
let factory = this.resolver.resolveComponentFactory(HelloComponent);
this.helloRef = factory.create(this.injector);
this.helloCopyRef = factory.create(this.injector);
factory = this.resolver.resolveComponentFactory(GoodbyeComponent);
this.byeRef = factory.create(this.injector);
}
show(){
this.theHost.detach();
this.theHost.insert(this.helloRef.hostView);
this.theHost.insert(this.byeRef.hostView);
this.theHost.insert(this.helloCopyRef.hostView);
}
Check this link for demo: https://stackblitz.com/edit/angular-4aus6a