Use case: I am building a toast notification service, ToastService. I want to be able to inject this service into components to create new toasts.
I have created a Toast component which represents a single notification:
@Component({
selector: 'toast',
template: `<div>This is a notification</div>`
})
export class Toast {}
And the I want to be able to call toastService.show(myMessage); to display a toast from one of my components.
So far my ToastService looks like this:
@Injectable()
export class ToastService{
constructor(private loader: DynamicComponentLoader) {}
show(message: string) {
this.loader.loadNextToLocation(
Toast,
/* location: ElementRef - how do I get one? I want to load it into the body */
)
.then((ref: ComponentRef) => {
console.log('loaded toast!');
});
}
}
I would ideally like to load the toast as a child of the body element, to ensure it is always on top of the rest of the app elements.
How is this possible? Or is there a better approach? I tried to figure out how they do it in the angular2 material repo, but it is just too hard for me to understand.