I'm trying to implement snackbar angular material component on my project. https://stackblitz.com/angular/ygomllvemnl?file=src%2Fapp%2Fsnack-bar-component-example.ts
This element(component) is used by 3 other components. So I need to implement the exact same method 'openSnackBar' in each component, and that will make redundancy on my code.
So what is the best place to implement the shared method 'openSnackBar', service class, helper class..., and then I can call it with one line of code?
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.