1

I'm creating a component that receives another component through an input which you can see in this stackblitz demo. If you look at the @Input() of the ParentComponent you'll see it's defined as

@Input() ComponentToEmbed : eComponentType<Component>;

I came across this StackOverflow question from 4 years ago, which suggested using ComponentType<T>, which is what made me try it. However, in my Angular 13 app, there is no such a thing as ComponentType being found when I begin typing. I looked on the doc pages and didn't see anything mentioning ComponentType<T>. What should I do to type the @Input() properly?

Naeem Khoshnevis
  • 2,001
  • 4
  • 18
  • 30
Optiq
  • 2,835
  • 4
  • 33
  • 68

2 Answers2

2

ComponentType<T> is part of Angular Material CDK

/** Interface that can be used to generically type a class. */
export interface ComponentType<T> {
    new (...args: any[]): T;
}
Vikas
  • 11,859
  • 7
  • 45
  • 69
  • aahhhh ok that explains why I can't find it anywhere in Angulars code or docs, that's a huge help lol. – Optiq Jan 10 '22 at 22:01
1

Based on you stackblitz example, it looks like Type<Component> should do the trick.

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

@Input() ComponentToEmbed : Type <Component>;
...
  • This works in my `ParentComponent` but if you look at my `AppComponent` in the stackblitz where I initially import it to pass into the `ParentComponent` it says the component isn't assignable to `Type` because it doesn't have properties in common with `Component`. So in my `AppComponent` I have to leave it as type `any`. Would you happen to know why that is? – Optiq Jan 10 '22 at 22:05
  • I created a more generic approach, but it's hard to make it type-strict or type-safe, since there is no common prototype for all Components, since `Component` is not a base class component but rather just a decorator or in simpler terms: a helper function. Therefore there is no way to make some field that would only accept Component constructor functions without introducing a new base class for all children components. However, you can make sure that the passed value is a constructor function, and using some conditional typing even to narrow it more precisely. – A. Milosavljević Jan 10 '22 at 23:49
  • The example I mentioned above is here: https://stackblitz.com/edit/angular-ivy-g7uqhg?file=src%2Fapp%2Fparent-component%2Fparent.component.ts – A. Milosavljević Jan 10 '22 at 23:49