动态创建同一组件的多个实例。

3

在Angular中有没有一种动态创建多个相同组件实例的方法?我已经尝试使用componentFactory,但没有成功。


你遇到了什么问题?你能提供一些展示你如何解决它的代码吗? - Daniel W Strimpel
我刚在 StackBlitz 上创建了一个简化的示例,它实际上是可以工作的。当我们尝试在我们的应用程序中运行时,一定做错了什么。无论如何,如果有人想知道如何操作,这里是链接:https://stackblitz.com/edit/angular-4aus6a。 - Yhlas
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);
}

点击以下链接查看演示:https://stackblitz.com/edit/angular-4aus6a


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接