Angular (v5+) - Snackbar "openFromComponent", component communication

Cody Tolene picture Cody Tolene · May 18, 2018 · Viewed 13.8k times · Source

Angular (v5.2.10) Snackbar

--| Intro |--
I have one Angular component (let's call it "Parent") initializing an Angular material Snackbar called snackBar. Passed in is SnackbarMessage , another component with a template containing the snackbar markup. Using snackBar.openFromComponent(SnackBarMessage) is necessary in this instance because I need to use more than just plain text in the snackbar [like markup, click events, etc] where snackBar.open(message, action) is not enough.

--| Code |--

"Parent" component:

@Component({
  selector: 'app-parent',
  templateUrl: './parent.component.html'
})
export class Parent implements AfterViewInit {

  public constructor(public snackBar: MatSnackBar) { }

  public ngAfterViewInit(): void {
      this.snackBar.openFromComponent(SnackbarMessage);
  }

  public dismissSnackbar(): void {
    this.snackBar.dismiss();
  }
}

"SnackbarMessage" component:

@Component({
  selector: 'app-snackbar-message',
  templateUrl: './snackbar-message.html'
})
export class SnackbarMessage { }

"snackbar-message.html" markup:

<p>(Snackbar message)</p>
<button type="button" (click)="dismissSnackbar();">Dismiss</button>


--| Issue |--
Within the imported SnackbarMessage template (snackbar-message.html) I need to call the Parent component's dismissSnackbar();, how do we do this with the current encapsulation of this Angular app?

Answer

Yatharth Varshney picture Yatharth Varshney · May 18, 2018

You don't actually need to call the parent component's "dismissSnackbar()" method to dismiss the snackbar. You can simply inject the "MatSnackBar" into the "SnackbarMessage" component and call "dismiss()" method on that injected instance of "MatSnackBar". As written in the docs, this will hide the currently visible Snackbar i.e. the Snackbar opened using "SnackbarMessage" component in your example. Below is your updated "SnackbarMessage" component:-

"SnackbarMessage" component:

@Component({
    selector: 'app-snackbar-message',
    templateUrl: './snackbar-message.html'
})
export class SnackbarMessage { 
    constructor(public snackBar: MatSnackBar) {}

    public dismissSnackbar(): void {
        this.snackBar.dismiss();
    }
}