在MatSnackBar中插入一个链接

时间:2017-10-26 08:25:10

标签: angular angular-material2

是否可以在Angular Material 2 MatSnackBarModule中插入链接?

我已经尝试在文本中执行此操作,但它将html显示为文本。

const text = '<a routerLink="/login">login</a>';
this.snackBar.open(text, 'OK', {
  duration: environment.snackBarTime,
});

3 个答案:

答案 0 :(得分:8)

您必须为链接创建自己的自定义零食栏组件:

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 {}

另外,请确保在应用的模块文件中的declarationsentryComponents下声明此自定义小吃栏:

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 {}

第三,要打开此零食栏组件,请调用openFromComponent的{​​{1}}方法:

MatSnackBar

app.component.ts

最后,我建议你在快餐栏中的锚元素中添加一个类,因为它看不清楚。

这是一个demo供你玩。

答案 1 :(得分:1)

如果您要做的就是在用户单击小吃栏操作时导航用户,那么有一个更直接的解决方案,无需创建专用组件。

this.snackBar.open('Record has been created', 'View Record', { duration: 5000})
  .onAction()
  .subscribe(() => this.router.navigateByUrl('/app/user/detail'));

答案 2 :(得分:0)

这里有点晚了,但您也可以在组件的 html 文件中创建一个模板,然后使用 snackbar.openFromTemplate() 从打字稿文件中调用它。

这与@Edric 的回答非常相似,但允许使用动态消息而不是静态消息。

这里有一个很好的演示说明如何做到这一点:https://github.com/angular/components/blob/master/src/dev-app/snack-bar/snack-bar-demo.ts