在MatSnackBar中插入一个链接

Den*_* M. 3 angular-material2 angular

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

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

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

Ste*_*aul 14

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

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


Edr*_*ric 10

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

custom-snackbar.component.html:

<a routerLink="/login">Login</a>
Run Code Online (Sandbox Code Playgroud)

custom-snackbar.component.ts:

import { Component } from '@angular/core';

@Component({
  selector: 'custom-snackbar',
  templateUrl: 'custom-snackbar.component.html'
})
export class CustomSnackBar {}
Run Code Online (Sandbox Code Playgroud)

此外,还要确保这一习俗小吃吧是根据申报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 {}
Run Code Online (Sandbox Code Playgroud)

第三,要打开这个零食栏组件,请调用以下openFromComponent方法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 };
  }
}
Run Code Online (Sandbox Code Playgroud)

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

这是一个你可以玩的演示.

  • @Developer这是angular和rxjs的已知错误.你可以谷歌了解它. (2认同)