Created
July 16, 2017 01:02
-
-
Save caroso1222/2f8afb416fe276153e9ef85d6b1e937f to your computer and use it in GitHub Desktop.
Angular CDK - Portal and PortalHost
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 { | |
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