To achieve this you need to create one shared service to share between multiple component. Make sure you add ToastService in Providers array in module.
@Injectable()
export class ToastService {
public duration = 3000;
public horizontalPosition: 'left' | 'start' | 'end' | 'right' | 'center' | undefined = 'left';
public verticalPosition: 'bottom' | 'top' | undefined = 'bottom';
constructor(private snackBar: MatSnackBar) { }
public saveToast(
message = 'Save Successful.',
duration = this.duration,
horizontalPosition = this.horizontalPosition,
verticalPosition = this.verticalPosition
) {
this.snackBar.openFromComponent(ToastComponent, {
data: message,
duration,
horizontalPosition,
verticalPosition
});
}
}
Then in your toast component you have to add code to display snackbar. Make sure you add ToastComponent declaration and entrycomponents array in ur module:
import { Component, Inject } from '@angular/core';
import { MAT_SNACK_BAR_DATA, MatSnackBar } from '@angular/material';
@Component({
selector: 'general-toast',
template: `
<div>
<div>
<span [innerHTML]="data> </span>
</div>
<div>
<button mat-icon-button (click)="dismissToast()">
<mat-icon>close</mat-icon>
</button>
</div>
</div>
`,
})
export class ToastComponent {
constructor(
@Inject(MAT_SNACK_BAR_DATA) public data: any,
public snackBar: MatSnackBar
) { }
public dismissToast(): void {
this.snackBar.dismiss();
}
}
You are all set now. You just need to Inject ToastService in the constructor and call from your component.