Insert a link into MatSnackBar

前端 未结 2 1974
太阳男子
太阳男子 2021-01-06 04:03

Is it possible to insert a link into the Angular Material 2 MatSnackBarModule?

I\'ve tried doing it inside the text, but it displays the html as text.

相关标签:
2条回答
  • 2021-01-06 04:19

    If all you want to do is navigate the user when they click on the snackbar action, then there is a much more straightforward solution to this which does not involve creating a dedicated component.

    this.snackBar.open('Record has been created', 'View Record', { duration: 5000})
      .onAction()
      .subscribe(() => this.router.navigateByUrl('/app/user/detail'));
    
    0 讨论(0)
  • 2021-01-06 04:26

    You have to create your own custom snackbar component for links:

    custom-snackbar.component.html:

    <a routerLink="/login">Login</a>
    

    custom-snackbar.component.ts:

    import { Component } from '@angular/core';
    
    @Component({
      selector: 'custom-snackbar',
      templateUrl: 'custom-snackbar.component.html'
    })
    export class CustomSnackBar {}
    

    Also, ensure that this custom snackbar is declared under declarations and entryComponents in your app's module file:

    app.module.ts:

    import { CustomSnackBar } from './custom-snackbar/custom-snackbar.component';
    import { NgModule } from '@angular/core';
    import { MatSnackBarModule } from '@angular/material';
    // Other module imports here
    
    @NgModule({
        declarations: [
          CustomSnackBar
          // Other declarations here
        ],
        imports: [
          MatSnackBarModule,
          // Other modules here
        ],
        entryComponents: [
          CustomSnackBar
        ]
    })
    export class AppModule {}
    

    Thirdly, to open this snackbar component, call the openFromComponent method of MatSnackBar:

    app.component.ts:

    import { MatSnackBar } from '@angular/material';
    import { CustomSnackBar } from './custom-snackbar/custom-snackbar.component';
    export class AppComponent {
      constructor(private snackbar: MatSnackBar){}
    
      login() {
        /*
         * `openFromComponent` accepts two properties:
         * The first param is `ComponentType<any>`, or your snackbar 
         * component
         * The second param is `MatSnackBarConfig`. In this sample,
         * I'll be using the duration param.
         */
        this.snackbar.openFromComponent(CustomSnackBar, { duration: 5000 };
      }
    }
    

    Lastly, I recommend you to add a class to the anchor element in the snackbar as it can't be seen clearly.

    Here's a demo for you to play around with.

    0 讨论(0)
提交回复
热议问题