0

I'm implementing a relatively complex component loader in Angular, and I'd like to dynamically get the component instance from a rxjs store.

loadEditAreaComponent(component: any, componentInstanceData?: {}){
    const componentFactory = this.cfr.resolveComponentFactory(component);
    const viewContainerRef = this.editAreaHost.viewContainerRef;
    const componentRef = viewContainerRef.createComponent(componentFactory);
    Object.keys(componentInstanceData).forEach(key => {
      componentRef.instance[key] = componentInstanceData[key];
})

It works. However, I'm feeling any is a little sloppy here. I can't seem to find the correct type.

The signature of resolveComponentFactory is (method) ComponentFactoryResolver.resolveComponentFactory<unknown>(component: Type<unknown>): ComponentFactory<unknown>.

When I'm saying component: Type I'm getting: Argument of type 'Type' is not assignable to parameter of type 'Type<unknown>'.

When I'm saying component: Type<unknown> or Type<any> I'm getting: Type 'Type' is not generic.

Would appreciate assistance, and would also love to get some background regarding the Typescript constraints I'm probably failing to understand.

Thank you!

noamyg
  • 2,747
  • 1
  • 23
  • 44

1 Answers1

1

The signature of resolveComponentFactory method looks like:

abstract resolveComponentFactory<T>(component: Type<T>): ComponentFactory<T>;

You should be using the same type:

import { Type } from '@angular/core';

loadEditAreaComponent<T>(component: Type<T>, ...
yurzui
  • 205,937
  • 32
  • 433
  • 399
  • Thanks, I guess that the `Type` should have worked, and I probably imported `Type` from the wrong path. – noamyg Aug 12 '20 at 11:09