Lars-Kristian Johansen
Lars-Kristian Johansen

Reputation: 160

Angular 4: Argument of type 'typeof CLASS' is not assignable to parameter of type 'INTERFACE'

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?

Upvotes: 3

Views: 2966

Answers (2)

yurzui
yurzui

Reputation: 214235

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

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

Plunker Example

Upvotes: 4

DeborahK
DeborahK

Reputation: 60578

It appears that the openComponent method is expecting an instance:

   const demoComponent = new DemoComponent()

   ...

   openComponent(demoComponent, null);

Upvotes: 1

Related Questions