Here is my approach
- Start by creating a component
- Next, develop a Service specifically for handling snack bars
- Add the component to a module by importing it in both declarations and entryComponents
- Now you can effectively utilize the service
For demonstration purposes, consider the following example:
my-snackbar.component.ts
import { Component, OnInit, Inject } from '@angular/core';
import { MAT_SNACK_BAR_DATA } from '@angular/material/snack-bar';
@Component({
selector: 'my-snackbar',
templateUrl: './snackbar.component.html',
styleUrls: ['./snackbar.component.scss']
})
export class MySnackbarComponent implements OnInit {
constructor(@Inject(MAT_SNACK_BAR_DATA) public data: any) {
console.log(data);
}
ngOnInit() {}
get getIcon() {
switch (this.data.snackType) {
case 'Success':
return 'done';
case 'Error':
return 'error';
case 'Warn':
return 'warning';
case 'Info':
return 'info';
}
}
}
.........
my-snackbar.component.html
<div fxLayout="row" class="snack-container">
<div>
<mat-icon>{{getIcon}}</mat-icon>
</div>
<div>
<span>{{data.message}}</span>
</div>
</div>
.........
my-snack-bar.service.ts
import { Injectable } from '@angular/core';
import { MatSnackBar } from '@angular/material/snack-bar';
import { MySnackbarComponent } from '../components/snackbar/my-snackbar.component';
@Injectable({
providedIn: 'root'
})
export class MySnackBarService {
constructor(private snackBar: MatSnackBar) {}
public openSnackBar(message: string, action: string, snackType?: snackType) {
const _snackType: snackType =
snackType !== undefined ? snackType : 'Success';
this.snackBar.openFromComponent(SnackbarComponent, {
duration: 2000,
horizontalPosition: 'end',
verticalPosition: 'top',
data: { message: message, snackType: _snackType }
});
}
}
........
app.module.ts
@NgModule({
declarations: [
SnackbarComponent
],
imports: [
...
],
providers: [],
bootstrap: [AppComponent],
entryComponents: [
SnackbarComponent
]
})
export class AppModule {}
.......
other.component.ts
import { Component, OnInit } from '@angular/core';
import { MySnackBarService } from '../../services/my-snack-bar.service';
@Component({
...
})
export class SomeComponent implements OnInit {
constructor(
private snack: MySnackService
) {}
ngOnInit() {
}
openSnack() {
this.snack.openSnackBar('Testing snack', '', 'Success');
}
}