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

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>

You can do the following to achieve this.

This snack-bar is like a mat-dialog.. you have to call the dismiss() on a MatSnackBarRef

DI renderer and MatSnackBarRef... you don't need renderer if you are going to dismiss some other way, this is just for demonstration purposes.

 @Inject(MAT_SNACK_BAR_DATA) public data,
    private _snackRef: MatSnackBarRef<UploadProgressComponent>,
    private ren:Renderer2

If you wanted to dismiss on progress bar completing you could call dismiss() in that logic. I am going to dismiss on click.

Create click event listener in your constructor...

{ 
  setTimeout(()=>{
    let snackEl = document.getElementsByClassName('mat-snack-bar-container').item(0);
    ren.listen(snackEl, 'click', ()=>this.dismiss())
  })

create your dismiss()

  dismiss(){
    this._snackRef.dismiss();
  }

Stackblitz

https://stackblitz.com/edit/angular-mdyher?embed=1&file=app/snack-bar-component-example.ts


Marshal's solution is nice but requires a lot of effort.

The following solution is cleaner (No need to pass snack bar reference or listen to any dom event)

Stackblitz

Snackbar component:

@Component({
  selector: 'app-upload-progress-snackbar',
  template: `
  Hello :)
  <button mat-button color="primary" (click)="dismiss()">Dismiss</button>  
  `,

})
export class UploadProgressComponent {
  constructor(
    @Inject(MAT_SNACK_BAR_DATA) public data) {}

  dismiss(){
    this.data.preClose(); //access preClose function when you want to close snackbar
  }
}

Snackbar opener code:

openSnackBar() {
    const snackBar = this.snackBar.openFromComponent(UploadProgressComponent, {
      data: {preClose: () => {snackBar.dismiss()} } //pass a function to be called when you want to close the snackbar
    });
  }