Angular2: Insert a dynamic component as child of a container in the DOM

前端 未结 6 1882
长发绾君心
长发绾君心 2020-11-29 03:44

Is there a way to insert dynamically a component as a child (not a sibling) of a DOM tag in Angular 2?

There are plenty of examples around there to

6条回答
  •  孤城傲影
    2020-11-29 04:05

    My Solution would be quite similar to @Bohdan Khodakivskyi. But I tried to the Renderer2.

      constructor(
        private el: ElementRef,
        private viewContainerRef: ViewContainerRef,
        private componentFactoryResolver: ComponentFactoryResolver,
        private render: Renderer2
      ) {}
    
      ngOnInit() {
        const componentFactory = this.componentFactoryResolver.resolveComponentFactory(
          MyDynamicComponent,
        );
        const componentRef = this.viewContainerRef.createComponent(componentFactory);
        this.render.appendChild(this.el.nativeElement, componentRef.location.nativeElement)
      }
    

提交回复
热议问题