jxycms
9/4/2019 - 4:45 AM

angular material snack bar design and implementation

Toast Component

Html:

<div class="toast">
  <div class="toast-icon">
    <i class="far fa-times-circle" *ngIf="data?.type=='Error'"></i>
    <i class="far fa-check-circle" *ngIf="data?.type=='Success'"></i>
    <i class="fas fa-exclamation-triangle" *ngIf="data?.type=='Warning'"></i>
    <i class="fas fa-info-circle" *ngIf="data?.type=='Info'"></i>
  </div>
  <div class="toast-message">
    <div class="toast-title">{{data?.type}}</div>
    <div class="toast-content">{{data?.message}}</div>
  </div>
</div>

Component:

import { Component, OnInit, Inject } from '@angular/core';
import { MAT_SNACK_BAR_DATA } from '@angular/material';

@Component({
  selector: 'app-toast',
  templateUrl: './toast.component.html',
  styleUrls: ['./toast.component.css']
})
export class ToastComponent implements OnInit {

  constructor(@Inject(MAT_SNACK_BAR_DATA) public data: any) { }

  ngOnInit() {
  }
}

CSS:

.toast-icon {
    align-items: center;
    font-size: 16px;
    height: 24px;
    -ms-flex-pack: center;
    justify-content: center;
    margin-right: 14px;
    width: 24px;
}

.toast {
    border-radius: 2px;
    display: -ms-inline-flexbox;
    display: inline-flex;
    font-size: 14px;
    overflow: hidden;
    position: relative;
    width: 300px;
    height: auto;
}

.toast-title {
    font-size: 15px;
    font-weight: bold;
    letter-spacing: .5px;
}

.toast-content {
    padding: 10px 0;
    word-break: break-word;
    word-wrap: break-word;
}

.toast-message {
    align-self: center;
    -ms-flex-direction: column;
    flex-direction: column;
    overflow: hidden;
    width: inherit;
    word-break: break-word;
}

.SuccessToast {
    background-color: #4d831e;
}

.WarningToast {
    background-color: #c15601;
}

.InfoToast {
    background-color: #0677d5;
}

.ErrorToast {
    background-color: #d74113;
}

Service:

toastConfig = (message: string, type: 'Success' | 'Error' | 'Info' | 'Warning'):MatSnackBarConfig => {
    return {
        duration: 1500,
        data: {message: message, type: type},
        horizontalPosition: "right",
        verticalPosition: "top",
        panelClass: type+"Toast"
      }
}

Appication:

this.snackBar.openFromComponent(ToastComponent, this.Service.toastConfig("test", "Warning"));