How to use SnackBar on service to use in every component in Angular 2

前端 未结 4 2132
情深已故
情深已故 2020-12-15 06:19

I have a working snackbar, but it is only on each component, I want to add it on my service so I will just call it. This is my sample on my component.ts

4条回答
  •  旧巷少年郎
    2020-12-15 06:37

    You can easily do this . Please find below the example for the sample which i used in one of my projects and it works perfectly fine

    import { Injectable } from '@angular/core';
    import {
      MatSnackBar,
      MatSnackBarConfig,
      MatSnackBarHorizontalPosition,
      MatSnackBarVerticalPosition,
      MatSnackBarRef
    } from '@angular/material';
    
    @Injectable()
    export class SnackBarService {
    
      snackBarConfig: MatSnackBarConfig;
      snackBarRef: MatSnackBarRef;
      horizontalPosition: MatSnackBarHorizontalPosition = 'center';
      verticalPosition: MatSnackBarVerticalPosition = 'top';
      snackBarAutoHide = '1500';
    
      constructor(private snackBar: MatSnackBar) { }
    
      openSnackBar(message) {
        this.snackBarConfig = new MatSnackBarConfig();
        this.snackBarConfig.horizontalPosition = this.horizontalPosition;
        this.snackBarConfig.verticalPosition = this.verticalPosition;
        this.snackBarConfig.duration = parseInt(this.snackBarAutoHide, 0);
        this.snackBarConfig.panelClass = 'custom-snackbar';
        this.snackBarRef = this.snackBar.open(message, '', this.snackBarConfig);
    }
    
    }
    

    Now , you only need to inject this service in your component or where ever you want to use it and call openSnackBar() method with the message you want to show.

    Hope this helps!!

提交回复
热议问题