在 MatSnackBar 中插入链接 [英] Insert a link into 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 {}
此外,请确保在您的应用模块文件中的 declarations
和 entryComponents
下声明此自定义小吃店:
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 {}
第三,要打开这个snackbar组件,调用MatSnackBar
的openFromComponent
方法:
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屋!