I am currently working on developing a modal generator service that will be used to create different types of modals.
One issue I am facing is with the syntax in the function declaration. The current code looks like this:
private createModalComponent (compType : Type<Component>, vCref: ViewContainerRef): ComponentRef<compType> { ... }
However, this is resulting in an error stating "cannot find name 'compType'". I then attempted a more generic approach:
private createModalComponent<T> (compType : T, vCref: ViewContainerRef): ComponentRef<T> { ... }
But this led to an error saying "Argument of type 'T' is not assignable to parameter of type 'Type<{}>'. So now I'm stuck on how to return a dynamically typed object in TypeScript.
import { Injectable, ViewChild, ViewContainerRef, ElementRef,
EventEmitter, OnInit, ComponentRef, ComponentFactoryResolver,
Type, ReflectiveInjector } from '@angular/core';
import { WizardModalComponent } from './wizard-modal/wizard-modal.component'
@Injectable()
export class ModalGeneratorService {
constructor(private _cmpFctryRslvr: ComponentFactoryResolver, private _vcRef: ViewContainerRef) {}
private createModalComponent (compType : Type<Component>, vCref: ViewContainerRef): ComponentRef<compType> {
let factory = this._cmpFctryRslvr.resolveComponentFactory(compType);
// vCref is needed cause of that injector..
let injector = ReflectiveInjector.fromResolvedProviders([], vCref.parentInjector);
// create component without adding it directly to the DOM
let comp = factory.create(injector);
return comp;
}
createWizardModalcomponent(vCref : ViewContainerRef) {
createModalComponent(WizardModalComponent, vCref);
}
}