【问题标题】:Is there a way i can position Snackbar inside @ngmodule?有没有办法可以将 Snackbar 定位在@ngmodule 中?
【发布时间】:2021-09-17 08:02:00
【问题描述】:

我在多个组件中使用snackbar,所以我决定在主模块中设置持续时间,我想将位置添加为顶部

这是我的 app.module.ts


import { MatSnackBar, MatSnackBarVerticalPosition, MAT_SNACK_BAR_DEFAULT_OPTIONS } from '@angular/material/snack-bar';
.
.

@NgModule({
  declarations: [],
  imports: [],
  providers: [
    {provide: MAT_SNACK_BAR_DEFAULT_OPTIONS, useValue: {duration: 1500}}
  ],
  bootstrap: [AppComponent]
})
export class AppModule {

 }

编辑: 小吃栏方法在另一个组件中是相同的。当我将其添加到组件方法时,它会显示错误:

'{ verticalPosition: any; 类型的参数}' 不可分配给“字符串”类型的参数。

当我添加持续时间时发生了同样的情况。

商品组件

import { MatSnackBar, MatSnackBarHorizontalPosition, MatSnackBarVerticalPosition } from '@angular/material/snack-bar';


@Component({})
export class CommodityListComponent implements OnInit {

 displayedColumns: string[] = [''];
 
 verticalPosition: MatSnackBarVerticalPosition = 'top';

 constructor(public svc: CommodityServiceService, private dialog: MatDialog,private _snackBar: MatSnackBar) { }
   getList() {
     this.svc.getCommodities();
   }

 ngOnInit() {
   this.getList();
 }
 Edit(e:any) {
  this.svc.Edit(e);
  const conf = new MatDialogConfig();
  conf.width = "30%";
  this.dialog.open(CommodityComponent, conf);
}
 openDialog() {
  this.svc.form.reset();
  const conf = new MatDialogConfig();
  conf.width = "30%";
  this.dialog.open(CommodityComponent, conf)
}
DeleteCommodity(e: any){
  debugger
  this.svc.DeleteRecord(e).subscribe(e => {
    this.openSnackBar("Record Deleted");
    this.svc.getCommodities();
  });
}
openSnackBar(message: string) {
  this._snackBar.open(message);
  
}
}

我正在使用角度 12.0.1

【问题讨论】:

  • 你尝试了什么?什么不工作?
  • 你可以创建一个自定义组件包装器/服务(我不记得snackbar 是如何工作的),其中包含snackbar 选项并始终使用它而不是原始选项。
  • 我在我的 opensnackbar 方法中添加了位置,但它显示 `Argument of type '{ this: any;顶部:任何; }' 不可分配给“字符串”类型的参数。 `
  • 编辑您的问题并向我们展示您的代码
  • 当我向这个方法添加持续时间时发生了同样的情况,所以我在 ngModule 中添加了持续时间

标签: angular angular-material angular12


【解决方案1】:

在我的情况下,我没有在我的 openSnackbar 方法中添加操作字符串,它看起来像这样:

openSnackBar(message: string) {
  this._snackBar.open(message,{
    verticalPosition:this.verticalPosition
  }
 );  
}

我认为这是显示错误的原因。所以,我添加了action: string 参数并将"" 作为参数传递,我的方法看起来像这样:

openSnackBar(message: string,Action:string) {
  this._snackBar.open(message,Action,{
    verticalPosition:this.verticalPosition
  }
  );
}

它有效!

【讨论】:

    猜你喜欢
    • 2017-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多