Created
November 17, 2022 21:32
-
-
Save joldibaev/a19fe76bd9771df129947926bb2dec15 to your computer and use it in GitHub Desktop.
Angular create component and add to app-root
This file contains hidden or 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
import {ApplicationRef, createComponent, Injectable} from '@angular/core'; | |
import {ModalComponent} from '../components/modal/modal.component'; | |
@Injectable() | |
export class ModalService { | |
constructor(private applicationRef: ApplicationRef) {} | |
createModal() { | |
// Get an `EnvironmentInjector` instance from the `ApplicationRef`. | |
const environmentInjector = this.applicationRef.injector; | |
// We can now create a `ComponentRef` instance. | |
const componentRef = createComponent(ModalComponent, { | |
environmentInjector, | |
}); | |
// Last step is to register the newly created ref using the `ApplicationRef` instance | |
// to include the component view into change detection cycles. | |
this.applicationRef.attachView(componentRef.hostView); | |
const root = document.getElementsByTagName('app-root')[0]; | |
root?.append(componentRef.location.nativeElement); | |
return componentRef; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment