Insert a link into MatSnackBar

前端 未结 2 1973
太阳男子
太阳男子 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:26

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

    custom-snackbar.component.html:

    Login
    

    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`, 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.

提交回复
热议问题