Skip to content

Instantly share code, notes, and snippets.

Embed
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';
@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
You can’t perform that action at this time.