Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert a link into MatSnackBar

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.

const text = '<a routerLink="/login">login</a>';
this.snackBar.open(text, 'OK', {
  duration: environment.snackBarTime,
});
like image 691
Deniss M. Avatar asked Oct 26 '17 08:10

Deniss M.


2 Answers

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.

like image 142
Edric Avatar answered Dec 18 '22 08:12

Edric


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'));
like image 22
Stephen Paul Avatar answered Dec 18 '22 08:12

Stephen Paul