How to inject snackBarRef into a component with op

2020-06-16 05:20发布

The latest Material documentation says the following..

If you want to close a custom snack-bar that was opened via openFromComponent, from within the component itself, you can inject the MatSnackBarRef.

but they don't show you how to do it.

In their example, they nest a component within the same .ts file as the calling module, and they don't show the ref being passed in. But since I want to use a more centralized approach, I have created a new module using...

ng g component components/snackbar

This way, I should be able to pass in @Input to render different html depending on need. This would further allow for things like branding, multiple buttons, and for html buttons to dismiss the snackbar… as long as they have access to a ref!

My calling .ts has the following...

var snackBarRef : any;
snackBarRef = this.snackBar.openFromComponent(SnackbarComponent, {data : snackBarRef});

the component .ts has the following constructor...

constructor(public snackBar: MatSnackBar, @Inject(MAT_SNACK_BAR_DATA) public data: any) { }

My expectations are that I could then create a function in the component that could act upon snackBarRef.dismiss(); as needed. However, when I run the app, I get the following error...

Uncaught (in promise): Error: StaticInjectorError(AppModule)[SnackbarComponent -> InjectionToken MatSnackBarData]: 
  StaticInjectorError(Platform: core)[SnackbarComponent -> InjectionToken MatSnackBarData]

Just to make sure I had the plumbing right, I swapped out {data : snackBarRef} to {data : 0}. By doing that, I don't see any errors and I can use the data value of 0 for other things, but of course I also don't have a handle on the ref to use locally.

Is there another way to pass the snackBarRef into the component other than using the data section of the openFromComponent? or, alternatively, is there a way to pass the ref through the data section without causing the error?

4条回答
倾城 Initia
2楼-- · 2020-06-16 05:32

I only did this in Angular component:

import { MatSnackBar } from '@angular/material/snack-bar';

@Component({
  selector: 'app-tucamara',
  templateUrl: './tucamara.component.html',
  styleUrls: ['./tucamara.component.scss']
})

export class TucamaraComponent implements OnInit {

snackBarRef: any;

constructor(private _snackBar: MatSnackBar) { }

ngOnInit(){

this.openSnackBar('El correo no existe en la BD por favor registrese.', 'Registrarme');
        this.snackBarRef.afterDismissed().subscribe(() => {
          console.log('::::::::::The snack-bar was dismissed'); // KYBC.Borrar.
          dosomething(); // KYBC.Do something!
        });

}

openSnackBar(mensaje: string, accion: string) {
    this.snackBarRef = this._snackBar.open(mensaje, accion, {
      duration: 5000, // KYBC.Time in milliseconds.
      verticalPosition: 'top', // KYBC.Posible values: 'top' | 'bottom'.
      horizontalPosition: 'center' // KYBC.Posible values: 'start' | 'center' | 'end' | 'left' | 'right'.
    });
  }
查看更多
Juvenile、少年°
3楼-- · 2020-06-16 05:35

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.

查看更多
聊天终结者
4楼-- · 2020-06-16 05:39

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.

查看更多
对你真心纯属浪费
5楼-- · 2020-06-16 05:45

Improving on Dario's answer, If one wants to capture the action button click in the calling component, one should use snackBarRef.dismissWithAction() in (click) event.

<button mat-raised-button color="accent" (click)="snackBarRef.dismissWithAction()">{{ data.action }}</button>
查看更多
登录 后发表回答