Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can define type of Component in Angular?

How can I define the type of Component in a dummy function?

@Component({
   templateUrl: 'a'
})
export class MyApp {
}
function dummy(component: any) {
     ....
}       
dummay(MyApp);
like image 337
Mahendra Hirapra Avatar asked Aug 30 '18 13:08

Mahendra Hirapra


People also ask

What is the type of a component in Angular?

Now, there are two types of component in Angular: Parent. Child.

What does a component class is defined to in Angular?

Components are a logical piece of code for Angular JS application. A Component consists of the following − Template − This is used to render the view for the application. This contains the HTML that needs to be rendered in the application. This part also includes the binding and directives.


1 Answers

There are a couple of different items in your question that could use clarification.

In your example export class MyApp {...} is creating a class of type MyApp.

Generally you would pass an instance of a class to a function. If that is what you are trying to do, then it would look as follows:

function dummy(component: MyApp) {
     ....
}       
dummay(new MyApp());

If you are actually trying to pass a class type to the function, then you would want to do the following:

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

function dummy(component: Type<any>) {
     ....
}       
dummay(MyApp);

Another way you could make this more powerful is if you restricted the components that could be passed to the function to only those that implement a given interface. An example of this would be as follows:

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

export interface IFoo {
   id: number;
   getStuff: () => string;
}
@Component({
   templateUrl: 'a'
})
export class MyApp implements IFoo {
}
function dummy(component: Type<IFoo>) {
     const stuff = component.getStuff();
     ....
}    

dummay(MyApp);
like image 85
peinearydevelopment Avatar answered Oct 01 '22 09:10

peinearydevelopment