Skip to content

Instantly share code, notes, and snippets.

@adrianfaciu
Created August 7, 2018 17:26
Show Gist options
  • Save adrianfaciu/1d236460c858362d889b4fd5a3110d81 to your computer and use it in GitHub Desktop.
Save adrianfaciu/1d236460c858362d889b4fd5a3110d81 to your computer and use it in GitHub Desktop.
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