Reputation: 1406
I am trying to create a reusable module. In that module, I want to feature to open different component using MatDialog
. Lets call the component StartActionComponent
. Normally, I can use:
export class StartActionComponent{
async startbuttonClicked(e: SomeEvent){
const dialogRef = this.dialog.open( SomeModalComponent , {data: e});
}
}
This works fine, but I want to dynamically inject a component , lets say SomeModalComponent2
. I am trying to achieve that as below:
DashboardModule
export const START_COMPONENT = new InjectionToken<any>('START_COM');
export class DashboardModule {
static forRoot(conf: {
onStart: any
}):ModuleWithProviders<DashboardModule>{
return {
ngModule: DashboardModule,
providers: [
{
provide: START_COMPONENT, useValue: conf.onStart
}
]
}
}
}
in StartActionComponent
component.
StartActionComponent
constructor(
@Inject(STOP_COMPONENT) startComponent: any) {}
async startbuttonClicked(e: SomeEvent){
const dialogRef = this.dialog.open( this.startComponent , {data: e});
}
and the in app.module.ts
AppModule
import { SomeModalComponent2 } from 'some.modal2.component`;
@NgModule({
import: [DashboardModule.forRoot(onStart: SomeModalComponent2)]
})
I want to remove any
and have a type for:
static forRoot(conf: {onStart: any})
or
@Inject(STOP_COMPONENT) startComponent: any) {}
I tried ComponentType but no luck
Upvotes: 6
Views: 1541
Reputation: 3253
so far I always used import { Type } from '@angular/core';
To quote the documentation
@description
Represents a type that a Component or other object is an instance of
An example of aType
isMyCustomComponent
class, which in JavaScript is represented by theMyCustomComponent
constructor function.
export declare const Type: FunctionConstructor;
As for the generic <T>
param, in your case you want to use any
. Then it will force you to provide a component of any type, but still a component - a number/bool/string/etc. input would be invalid
Alternative: I think ComponentType
from import { ComponentType } from '@angular/cdk/portal/portal';
. But requires you to install the cdk package and the interfaces look exactly the same (if you ignore the extend)
export interface ComponentType<T> {
new (...args: any[]): T;
}
// vs.
export declare interface Type<T> extends Function {
new (...args: any[]): T;
}
Upvotes: 0
Reputation: 142
I think I ran across a similair case whereas I wanted my dynamic components typed. So I made a new file called MyDynamicComponent.ts and it looked like this:
export type MyDynamicComponent = GridComponent | GridControlComponent | FeatureComponent | FeatureControlComponent;
In your case I believe it would be something like:
export type StartComponentType = SomeModalComponent | SomeModalComponent2;
I hope I understood your question correctly,
Upvotes: 0