Issue
I want to display an icon when displaying a message from the service message service which uses MatSnackBar
. (The Material module is imported in the app's module).
However, the default snackbar doesn't support an icon. How do I implement such a feature?
import { Injectable } from '@angular/core'
import {MatSnackBar} from '@angular/material/snack-bar';
import {MatSnackBarHorizontalPosition, MatSnackBarVerticalPosition} from "@angular/material";
@Injectable()
export class MessagesService {
horizontalPosition: MatSnackBarHorizontalPosition = 'right';
verticalPosition: MatSnackBarVerticalPosition = 'top';
constructor(private snackBar: MatSnackBar) {
}
info(message: string) {
const icon = `<mat-icon>info</mat-icon>`;
const msg = `${icon} ${message}`;
this.snackBar.open(msg, 'X', {
duration: 2000,
horizontalPosition: this.horizontalPosition,
verticalPosition: this.verticalPosition,
panelClass: ['info-message']
});
}
}
Solution
You have to use a custom snackbar component in order to show the icon. Thankfully, this should be similar to how you would define a dialog to show content, just that it's a snackbar instead of a dialog.
It's possible to pass in data to a snackbar, the same way as passing data to a dialog.
Note that when declaring a snackbar, you also have to import it in the entryComponents
property in the NgModule
declaration.
Here's an example:
icon-snack-bar.component.ts
import { MAT_SNACK_BAR_DATA } from '@angular/material/snack-bar';
// ...
@Component({
selector: '...',
template: `<mat-icon>{{ data?.icon }}</mat-icon> <span>{{ data?.message }}</span>`
// Most likely you have to add styles in order to position the icon, although I haven't tested it yet
export class IconSnackBarComponent {
constructor(@Inject(MAT_SNACK_BAR_DATA) public data: any) { }
}
my-component.component.ts
import { IconSnackBarComponent } from './icon-snack-bar/icon-snack-bar.component';
import { MatSnackBar } from '@angular/material/snack-bar';
// ...
export class MyComponent {
constructor(private snackBar: MatSnackBar) { }
openCustomSnackBar() {
this.snackBar.openFromComponent(IconSnackBarComponent, {
data: {
message: 'Hello, snackbar!',
icon: 'info'
}
});
}
}
app.module.ts
import { NgModule } from '@angular/core';
import { IconSnackBarComponent } from './icon-snack-bar/icon-snack-bar.component';
// ...
@NgModule({
declarations: [
// ...
IconSnackBarComponent
],
entryComponents: [
IconSnackBarComponent
]
})
export class AppModule { }
This is also partially covered in the docs here.
Answered By - Edric
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.