Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dismiss/close an Angular Snackbar element from inside element

I currently have a snackbar element with a mat-progress-bar inside it. I'd like to close the snackbar element. My code currently looks like this.

import { MAT_SNACK_BAR_DATA, MatSnackBar } from '@angular/material';
import { map } from 'rxjs/operators';

 @Component({
  selector: 'app-upload-progress-snackbar',
  template: `
  Progress:
  <mat-progress-bar mode="determinate" [value]="progress | async" *ngIf="progress !== undefined"></mat-progress-bar>`,
  styles: [`mat-progress-bar { margin-top: 5px;}`],
})
export class UploadProgressComponent {
  constructor(@Inject(MAT_SNACK_BAR_DATA) public data) { }

  private started = false;
  public progress = this.data.uploadProgress.pipe(
    map(({ loaded, total }) => {
      if (loaded === undefined) {
        return !this.started ? 0 : 100;
      } else {
        this.started = true;
        return Math.round(loaded / (total || loaded) * 100);
      }
    },
  ));
}

like image 864
Job Avatar asked Dec 06 '18 20:12

Job


People also ask

How do I close the SnackBar?

setAction("Dismiss", new View. OnClickListener() { @Override public void onClick(View v) { } }). show(); The snackbar can be dismissed by a swipe.

What is SnackBar used for?

Snackbars provide lightweight feedback about an operation. They show a brief message at the bottom of the screen on mobile and lower left on larger devices. Snackbars appear above all other elements on screen and only one can be displayed at a time.


1 Answers

A good way to do this is leveraging Dependency Injection inside the custom Snack Bar component to create a snack bar reference. Then close the component using this reference.

CustomSnackBar.ts

constructor(
    private snackBarRef: MatSnackBarRef<GeneralSnackbarComponent>,
    @Inject(MAT_SNACK_BAR_DATA) public data: any
) { }

public dismiss(): void {
    this.snackBarRef.dismiss();
    event.preventDefault();
}

CustomSnackBar.html

<button id="cancelBtn" mat-button (click)="dismiss()">
    Cancel
</button>
like image 119
Christopher Grigg Avatar answered Nov 16 '22 00:11

Christopher Grigg