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

前端 未结 6 1891
长发绾君心
长发绾君心 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:00

    I was searching for solution for same problem and approved answer not worked for me. But I have found better and much logical solution how to append dynamically created component as child to current host element.

    The idea is to use element reference of newly created component and append it to current element ref by using render service. We can get component object via its injector property.

    Here is the code:

    @Directive({
        selector: '[mydirective]'
    })
    export class MyDirectiveDirective {
        constructor(
            private cfResolver: ComponentFactoryResolver,
            public vcRef: ViewContainerRef,
            private renderer: Renderer2
        ) {}
    
        public appendComponent() {
            const factory = 
            this.cfResolver.resolveComponentFactory(MyDynamicComponent);
            const componentRef = this.vcRef.createComponent(factory);
            this.renderer.appendChild(
               this.vcRef.element.nativeElement,
               componentRef.injector.get(MyDynamicComponent).elRef.nativeElement
            );
        }
    }
    

提交回复
热议问题