2

I have dynamic created component using ComponentFactoryResolver. I want to insert this into template. I tried to use templateRef or viewContainerRef but not of them worked out.

ComponentOutlet expects component class not instance, ViewContainerRef expects template ref. None of them work with created instance.

How can make it work with created component instance ? Is there any way to do it ?

SOLUTION

I solved my problem using insert method of ViewContainerRef

2
  • Can you show what you tried? Commented Feb 14, 2021 at 20:43
  • ViewContainerRef has a createComponent method. Commented Feb 14, 2021 at 20:49

1 Answer 1

4

You need a reference to a view container:

export class ExampleComponent implements AfterViewInit {
@ViewChild('contentElement', { read: ViewContainerRef }) contentElement: ViewContainerRef;
    
    constructor(
        private componentFactoryResolver: ComponentFactoryResolver,
        private ref: ChangeDetectorRef
    ) {}
    
    ngAfterViewInit() {
            const componentFactory = this.componentFactoryResolver.resolveComponentFactory(
                yourComponent
            );

            const contentElement = this.contentElement;
            contentElement.clear();
            const component = contentElement.createComponent(componentFactory);
            this.ref.detectChanges();
        }
    }
<ng-template #contentElement></ng-template>
Sign up to request clarification or add additional context in comments.

1 Comment

I have dynamic created component using ComponentFactoryResolver as I state above I already have instantiniated component. createComponent method ViewContainerRef expects a class of ComponentType not an instance.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.