3

I am playing around with dynamic components in angular. But I have hit a problem I do not know how to solve.

I got this interface.

export interface InjectableComponent{
    setData(data: any): void;
}

Class implementing interface.

export class DemoComponent implements InjectableComponent {
    setData(data: any): void {

    }
}

Function using interface as argument type.

openComponent(component: InjectableComponent, data: any) {
    let componentFactory = this.componentFactoryResolver.resolveComponentFactory(<any>component);
    this.placeholder.clear();

    let componentRef = this.placeholder.createComponent(componentFactory);
    (<InjectableComponent>componentRef.instance).setData(data);
}

Calling function.

openComponent(DemoComponent, null); <-- ERROR

Getting this error:

Argument of type 'typeof DemoComponent' is not assignable to parameter of type 'InjectableComponent'.
Property 'setData' is missing in type 'typeof DemoComponent'.

Can someone explain to me why this is not working? A workaround maybe?

2
  • You can try changing method openComponent(component: Type<InjectableComponent> plnkr.co/edit/bbejmaGKXVpgiRRBo3lE?p=preview Commented Jul 10, 2017 at 19:50
  • Thanks that worked. If you make an answer I will accept it. :) Commented Jul 10, 2017 at 19:59

2 Answers 2

4

You can use special generic type Type<T> for that like

openComponent(component: Type<InjectableComponent>, data: any) {
   ...
}

Plunker Example

Sign up to request clarification or add additional context in comments.

Comments

1

It appears that the openComponent method is expecting an instance:

   const demoComponent = new DemoComponent()

   ...

   openComponent(demoComponent, null);

1 Comment

I can see that, but I need the class type. It is used with .resolveComponentFactory. I tried making the interface to an abstract class and then extending instead of implementing, but got a similar error.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.