Angular Material Snackbar: Add Icon Without Creating Another Component

只愿长相守 提交于 2020-08-10 19:19:58

问题


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:


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'
});


来源:https://stackoverflow.com/questions/62902786/angular-material-snackbar-add-icon-without-creating-another-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!