Skip to content

Instantly share code, notes, and snippets.

@joldibaev
Created November 17, 2022 21:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joldibaev/a19fe76bd9771df129947926bb2dec15 to your computer and use it in GitHub Desktop.
Save joldibaev/a19fe76bd9771df129947926bb2dec15 to your computer and use it in GitHub Desktop.
Angular create component and add to app-root
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