How to inject snackBarRef into a component with openFromComponent

空扰寡人 提交于 2019-12-04 07:19:10

I was stuck on the same problem today, but found the solution:

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

@Component({
  selector: 'my-notification',
  template: `
    <p>{{ data.message }}</p>
    <button mat-raised-button
            color="accent"
            (click)="snackBarRef.dismiss()">{{ data.action }}</button>
  `,
})
export class TestNotificationComponent {
  constructor(
    public snackBarRef: MatSnackBarRef<TestNotificationComponent>,
    @Inject(MAT_SNACK_BAR_DATA) public data: any,
  ) {}
}

Angular will handle injecting the snackBarRef.

By the way... in the meantime… I created a global variable (which I rarely do), and opened the snackbar with...

this.globals.snackBarRef = this.snackBar.openFromComponent(SnackbarComponent, {data : 0});

This way, I could use the data section to pass in the html section number I wanted to pop, and everything works fine. But I'd still be interested in the right way to do this.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!