-1

Is there method to Add Material Icon (Checkbox) Without Creating Another component in snackbar.

Maybe through PanelClass or API style parameter? We have 100s of different snackbars with simple text. Trying to refrain from creating 100 additional components if possible.

Need material checkbox (or any mat icon) in the left-align side of message.

How to add Icon inside the Angular material Snackbar in Angular 5

let snackBarMessage = `${this.products?.length} Successfully Added`;
this.snackBar.open(snackBarMessage, 'Close', {duration: 8000});

Need the following snackbar in design

Resource:

https://material.angular.io/components/snack-bar/api

1 Answers1

1

The best practice for this is going to be creating a new component, but you wont need 100 new components, 1 will do.

You can create a snackbar message component which you can inject any kind of object you wish to describe the behavior using @Inject(MAT_SNACK_BAR_DATA);

If you had an object snackbar-message-data.ts

export interface SnackbarMessageData {
  checkable: boolean;
  text: string;
  action: string;
  icon: string;
}
@Component({
  template: `
    <input *ngIf="data.checkable" type="checkbox" />
    <mat-icon *ngIf="data.icon">{{ data.icon }}</mat-icon>
    <span>{{ data.text }}</span>
    <button
      mat-raised-button
      color="accent"
      (click)="snackBarRef.dismiss()"
    >
      {{ data.action }}
    </button>
  `,
})
export class SnackbarMessageComponent {
  constructor(
    public snackBarRef: MatSnackBarRef<TestNotificationComponent>
    @Inject(MAT_SNACK_BAR_DATA) public data: any
  ) { }
}

And from the parent component opening the snackbar:

this.snackbar.openFromComponent(SnackbarMessageComponent, {
  checkable: true,
  text: `${this.products?.length} Successfully Added`,
  action: 'Close'
});
Chris Danna
  • 1,164
  • 8
  • 17
  • see thing is, one day, I may need a different mat icon, not only checkbox, however this answer is very helpful, thanks –  Jul 14 '20 at 20:32
  • then you can add an input to the data object. `icon: string;` and add to the template `{{data.icon}}` – Chris Danna Jul 14 '20 at 20:36
  • @marksmith542 I have edited the answer to reflect the need to pass in different icons. My example uses mat-icon but you can adjust to whichever icon library you are using. – Chris Danna Jul 14 '20 at 20:53