Last active
August 13, 2023 09:53
-
-
Save GreenFlag31/148c3a78fcc769c07b2dff5e4ab22c92 to your computer and use it in GitHub Desktop.
Modal service
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Injectable({ | |
providedIn: 'root', | |
}) | |
export class ModalService { | |
// Create a reference to our modal component | |
newModalComponent!: ComponentRef<ModalComponent>; | |
// Optional content passed at the creation : animation, size, ... | |
options!: Options | undefined; | |
constructor( | |
private appRef: ApplicationRef, | |
private injector: EnvironmentInjector | |
) {} | |
// To get clean function call signatures, I will use typescript function overloading | |
// Signature of the first approach | |
open( | |
vcrOrComponent: ViewContainerRef, | |
content: TemplateRef<Element>, | |
options?: Options | |
): void; | |
// Signature of the second approach | |
open<C>(vcrOrComponent: Type<C>, options?: Options): void; | |
// Function implementation | |
open<C>( | |
vcrOrComponent: ViewContainerRef | Type<C>, | |
param2?: TemplateRef<Element> | Options, | |
options?: Options | |
) { | |
if (vcrOrComponent instanceof ViewContainerRef) { | |
// For the first approach, we know that the second param will be of type TemplateRef, so we have to cast it | |
this.openWithTemplate(vcrOrComponent, param2 as TemplateRef<Element>); | |
this.options = options; | |
} else { | |
this.openWithComponent(vcrOrComponent); | |
// Same story here : for the second approach, the second param will be of type Options or undefined, since optional | |
this.options = param2 as Options | undefined; | |
} | |
} | |
private openWithTemplate(vcr: ViewContainerRef, content: TemplateRef<Element>) { | |
// We first start to clear previous views | |
vcr.clear(); | |
// We create a view with the template content | |
const innerContent = vcr.createEmbeddedView(content); | |
// We create the modal component, and project the template content in the ng-content of the modal component | |
this.newModalComponent = vcr.createComponent(ModalComponent, { | |
environmentInjector: this.injector, | |
projectableNodes: [innerContent.rootNodes], | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment