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

时间:2018-05-12 01:02:38

标签: javascript angular5

有没有办法以角度动态创建同一组件的多个实例?我已经尝试使用componentFacory,但没有成功。

1 个答案:

答案 0 :(得分:-1)

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