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

标签 javascript angular5

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

最佳答案

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

关于javascript - 动态创建同一组件的多个实例。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50301956/

相关文章:

javascript - 如何在 Firefox for Android 中检测 Android 的版本号?

javascript - 如何让 form::select 运行脚本来更改目标,以便每次选择不同选项时样式都会发生变化?

javascript - javascript中数组分割空值计数1

angular - 如何将 Angular 项目从 5 更新到 7

javascript - jQuery 检查输入值是否在数组中

javascript - css停止图像在滚动上移动

angular - 如何使用 NgModule 导出 const

css - <mat-card> 没有凸起 - 没有边框

javascript - 同时按日期和时间对数组进行排序?

javascript - RouterModule.forRoot() 调用了两次