3

I am building a application and part of the code allows developer to specify which component they want to render a certain part. I want users to know they need to implement an interface but I am not sure how to write typing correctly.

export interface ICustomComponent {
    templateObject: any;
}

export class MyComponent implements ICustomComponent {
}

export class MyLib {
    constructor(
        private yourComponent: ICustomComponent
    ) {}
}

new MyLib(MyComponent); <== Fails

I am writing code with Angular, and I cannot run new operator but let Angular to resolve and construct that component.

Here an example that illustrates my problem.

How to deal with this problem?

4
  • what do you want to pass here new MyLib(...);? Instance like new MyLib(new MyComponent()); or reference to the class? Commented Sep 18, 2017 at 5:02
  • angular.io/guide/dynamic-component-loader#resolving-components That example is to illustrate the problem only Commented Sep 18, 2017 at 5:11
  • so do you want to pass MyComponent to componentFactoryResolver.resolveComponentFactory(MyComponent);`? Commented Sep 18, 2017 at 5:19
  • Yes but it is being pass in decorator like @Config({ useComponent: MyComponent }) Commented Sep 18, 2017 at 5:20

1 Answer 1

2

Since MyLib expects a class constructor, not class instance, you need to define an interface for a class constructor and specify that it returns the instance with the ICustomComponent interface:

interface ICustomComponent {
  templateObject: any;
}

interface ICustomComponentConstructor {
  new (...deps: any[]): ICustomComponent;
}

And then you can use it like this:

export class MyComponent implements ICustomComponent {
  templateObject: any;
}

export class MyLib {
  constructor(private yourComponent: ICustomComponentConstructor) {
  }
}

new MyLib(MyComponent);

You can read about interface for class constructors and instances here.

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

Comments

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.