5

I have build a dialog service which dynamically create a DialogComponent with a child component.

I want my DialogComponent to be a generic class of <T> since i wish to type for whatever component child i'm using. I'm currently create my DialogComponent using theses lines ->

const componentFactory = this.componentFactoryResolver.resolveComponentFactory(DialogComponent);
const componentRef = componentFactory.create(new DialogInjector(this.injector, map));

The problem is that the resolveComponentFactory is actually returning a DialogComponent<{}> instead of T. I did try to cast but it's seem i can't because some methods is missing.

I'm wondering how i could achieve such thing !

Thanks.

EDIT

this.componentFactoryResolver.resolveComponentFactory<DialogComponent<T>> did the tricks..

Pilouk
  • 1,267
  • 1
  • 18
  • 36

2 Answers2

3

To get the right types, you need to pass the wanted type in the generic typing of resolveComponentFactory:

this.componentFactoryResolver.resolveComponentFactory<DialogComponent<T>>(DialogComponent);
Poul Kruijt
  • 69,713
  • 12
  • 145
  • 149
2

If you're sure about yourself, just bypass the type checking with a function.

myFunction<T>(className: T): { componentFactory: T, componentRef: any } {
  const componentFactory: T = this
    .componentFactoryResolver
    .resolveComponentFactory(className) as any;
  const componentRef = componentFactory
    .create(new DialogInjector(this.injector, map));
  return { componentFactory, componentRef };
}

const { componentFactory, componentRef } = myFunction(DialogComponent);

This might be an issue in the type definition of the framework. This code is a workaround, use it if you don't find anything else.