import { Component, ElementRef, OnDestroy, OnInit, ViewChild } from '@angular/core'; import { IcsToast } from './types/ics-toast'; import { IcsToastType } from './types/ics-toast-type'; import { IcsToastService } from './ics-toast.service'; import { isNullOrUndefined } from 'util'; import { animate, state, style, transition, trigger } from '@angular/animations'; import { Subscription } from 'rxjs'; import { NavigationEnd, NavigationStart, Router } from '@angular/router'; @Component({ selector: 'ics-toast', templateUrl: './ics-toast.component.html', styleUrls: ['./ics-toast.component.scss'], animations: [ trigger('flyInOut', [ state('in', style({opacity: 1, transform: 'translateX(0)'})), transition('void => *', [ style({ opacity: 0, transform: 'translateX(-100%)' }), animate('0.2s ease-in') ]), transition('* => void', [ animate('0.2s 0.1s ease-out', style({ opacity: 0, transform: 'translateX(100%)' })) ]) ]) ] }) export class IcsToastComponent implements OnInit, OnDestroy { readonly TIMEOUT = 5000; public toasts: IcsToast[]; public subscription: Subscription; constructor(private toastService: IcsToastService, private router: Router) { this.toasts = []; } ngOnInit() { this.router.events.subscribe(event => { if (event instanceof NavigationEnd) { this.toasts = this.toasts.filter(x => { let flag = false; if (x.keepAfterRouteChange) { x.keepAfterRouteChange = false; // keep only for one router change flag = true; } return flag; }); } }); this.subscription = this.toastService.toast$.subscribe((next: IcsToast) => { if (isNullOrUndefined(next)) { this.toasts = []; // clear the toasts } else { this.toasts.unshift(next); setTimeout(() => { this.popToast(); }, this.TIMEOUT); } }); } public textStyle(toast: IcsToast): any { let color = ''; if (toast.icon === IcsToastType.SUCCESS) { color = '#5CC1B6'; } else if (toast.icon === IcsToastType.LOADING) { color = '#fff'; } else if (toast.icon === IcsToastType.ERROR) { color = '#F26C4F'; } return { color: color }; } private popToast() { this.removeToast(this.toasts.length - 1); } public removeToast(index: number): void { this.toasts.splice(index, 1); } ngOnDestroy() { try { this.toasts = null; this.subscription.unsubscribe(); } catch (e) {} } }