3

Is there a way to dynamically create multiple instances of the same component in angular? I have tried it using componentFacory, but no success.

2
  • What problems did you run into? Can you provide any code showing how you did it? Commented 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. Commented May 12, 2018 at 6:10

1 Answer 1

4
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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.