将链接插入MatSnackBar [英] Insert a link into MatSnackBar

查看:64
本文介绍了将链接插入MatSnackBar的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我尝试在文本内部进行操作,但是它将html显示为文本.

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

推荐答案

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

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

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

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

第三,要打开小吃栏组件,请调用MatSnackBaropenFromComponent方法:

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.

这篇关于将链接插入MatSnackBar的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆