Angular 使用MatBottomSheet时,如何关闭浏览器背面的工作表

Angular 使用MatBottomSheet时,如何关闭浏览器背面的工作表,angular,angular-material,Angular,Angular Material,正如标题所说,我正在使用。当底部工作表打开并且用户单击浏览器的“后退”按钮时,他将被导航到远离打开底部工作表的页面。相反,我只想关闭“浏览器背面”的底部页面。 在Angular 5/6中实现这一点的最佳方法是什么?我通过链接使用了一个假的路由: this.location.go("#"); let sheet = this.bottomSheet.open(MyBottomSheetComponent, { data: { someData: someData }, }); let subs

正如标题所说,我正在使用。当底部工作表打开并且用户单击浏览器的“后退”按钮时,他将被导航到远离打开底部工作表的页面。相反,我只想关闭“浏览器背面”的底部页面。
在Angular 5/6中实现这一点的最佳方法是什么?

我通过链接使用了一个假的路由:

this.location.go("#");
let sheet = this.bottomSheet.open(MyBottomSheetComponent, {
  data: { someData: someData },
});
let subscription = this.location.subscribe(x => {
  if (x.url === 'this_is_the_URL_you_are_coming_from') {
    sheet.dismiss(true);
  } else {
    subscription.unsubscribe();
  }
});
sheet.afterDismissed().subscribe(x => {
  if (!x) {
    this.location.back();
  }
});

此技术也可用于“角度材质”的对话框组件。在我看来,它不是很地道,所以如果有人有一个更简单的方法来做这件事,请张贴一个答案

这里我使用的是角度6

要关闭底页,请执行以下操作:-

从“@angular/material”导入{MatBottomSheet}

在构造函数中添加底部工作表

构造器私有底板:MatBottomSheet { } 3.


就这样。一旦底部工作表打开并在关闭后将其关闭,将被激发。

使用angular 10,可以使用MatBottomSheetRef的释放方法。 这里有记录:


还有另一种方法可以处理返回键,并在返回键上关闭底部,它已经在Angular 10、浏览器和Android设备上进行了测试,我认为它适用于所有Angular版本

export class BottomSheetWidgetComponent implements OnInit {

  constructor(
    @Inject(MAT_BOTTOM_SHEET_DATA) private _data: any,
    private sheet: MatBottomSheetRef<BottomSheetWidgetComponent>

  ) {
    super(injector);
  }

  ngOnInit() {
    this.handleBackKey();
  }

  handleBackKey() {
    window.history.pushState(null, "Back", window.location.href);

    this.sheet.afterDismissed().subscribe((res) => {
      window.onpopstate = null;
      window.history.go(-1);
    });

    window.onpopstate = () => {
      this.sheet.dismiss();
      window.history.pushState(null, "Back", window.location.href);
    };
  }
 
}

我不是OP,但这帮了我的忙。我找不到那张纸。我试着用onDestroy。帮了我的忙,谢谢!我很高兴我迟来的回答对你有所帮助。
import { MatBottomSheet } '@angular/material/bottom-sheet';

class MyClass{
  constructor(private bottomSheet: MatBottomSheet){
  }

  context(){
    // opening bottomSheet
    let sheetRef = this.bottomSheet.open(MyComponent);
    // closing bottomSheet
    sheetRef.dismiss();
  }
}
export class BottomSheetWidgetComponent implements OnInit {

  constructor(
    @Inject(MAT_BOTTOM_SHEET_DATA) private _data: any,
    private sheet: MatBottomSheetRef<BottomSheetWidgetComponent>

  ) {
    super(injector);
  }

  ngOnInit() {
    this.handleBackKey();
  }

  handleBackKey() {
    window.history.pushState(null, "Back", window.location.href);

    this.sheet.afterDismissed().subscribe((res) => {
      window.onpopstate = null;
      window.history.go(-1);
    });

    window.onpopstate = () => {
      this.sheet.dismiss();
      window.history.pushState(null, "Back", window.location.href);
    };
  }
 
}