Skip to content

Instantly share code, notes, and snippets.

Created August 7, 2018 17:26
What would you like to do?
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';
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);
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