Skip to content

Instantly share code, notes, and snippets.

@caroso1222
Created July 16, 2017 01:02
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save caroso1222/2f8afb416fe276153e9ef85d6b1e937f to your computer and use it in GitHub Desktop.
Save caroso1222/2f8afb416fe276153e9ef85d6b1e937f to your computer and use it in GitHub Desktop.
Angular CDK - Portal and PortalHost
import {
Injectable,
ComponentFactoryResolver,
ApplicationRef,
Injector
} from '@angular/core';
import {
ComponentType,
Portal,
ComponentPortal,
DomPortalHost
} from '@angular/cdk';
@Injectable()
export class LoadingSpinnerService {
// 1. Reference to our Portal.
// This is the portal we'll use to attach our LoadingSpinnerComponent.
private loadingSpinnerPortal: ComponentPortal<LoadingSpinnerComponent>;
// 2. Reference to our Portal Host.
// We use DOMPortalHost as we'll be using document.body as our anchor.
private bodyPortalHost: DomPortalHost;
// 3. Inject the dependencies needed by the DOMPortalHost constructor
constructor(
private componentFactoryResolver: ComponentFactoryResolver,
private appRef: ApplicationRef,
private injector: Injector) {
// 4. Create a Portal based on the LoadingSpinnerComponent
this.loadingSpinnerPortal = new ComponentPortal(LoadingSpinnerComponent);
// 5. Create a PortalHost with document.body as its anchor element
this.bodyPortalHost = new DomPortalHost(
document.body,
this.componentFactoryResolver,
this.appRef,
this.injector);
}
reveal() {
// 6. Attach the Portal to the PortalHost.
this.bodyPortalHost.attach(this.loadingSpinnerPortal);
}
hide() {
// 7. Detach the Portal from the PortalHost
this.bodyPortalHost.detach();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment