Created
August 7, 2018 17:26
-
-
Save adrianfaciu/1d236460c858362d889b4fd5a3110d81 to your computer and use it in GitHub Desktop.
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
import { Injectable, Injector } from '@angular/core'; | |
import { Overlay } from '@angular/cdk/overlay'; | |
import { ComponentPortal, PortalInjector } from '@angular/cdk/portal'; | |
import { ToastComponent } from './toast.component'; | |
import { ToastData } from './toast-config'; | |
import { ToastRef } from './toast-ref'; | |
@Injectable({ | |
providedIn: 'root' | |
}) | |
export class ToastService { | |
constructor(private overlay: Overlay, private parentInjector: Injector) { } | |
showToast(data: ToastData) { | |
const overlayRef = this.overlay.create(); | |
const toastRef = new ToastRef(overlayRef); | |
const injector = this.getInjector(data, toastRef, this.parentInjector); | |
const toastPortal = new ComponentPortal(ToastComponent, null, injector); | |
overlayRef.attach(toastPortal); | |
return toastRef; | |
} | |
getInjector(data: ToastData, toastRef: ToastRef, parentInjector: Injector) { | |
const tokens = new WeakMap(); | |
tokens.set(ToastData, data); | |
tokens.set(ToastRef, toastRef); | |
return new PortalInjector(parentInjector, tokens); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment