如何从componentPortal实例中关闭材质覆盖

rob*_*ing 4 angular-material angular angular-cdk

我必须手动传递overlayRef,有没有更好的方法将它包含在带有DI的组件构造函数中?

服务代码:

display() {
    const overlayRef = this.overlay.create({
      positionStrategy: this.overlay.position().global().top(),
    });
    const portal = new ComponentPortal(ErrorsListBottomSheetComponent);
    this.ref = overlayRef.attach<ErrorsListBottomSheetComponent>(portal);
    this.ref.instance.overlayRef = overlayRef;
    overlayRef.backdropClick().subscribe(() => {
      overlayRef.detach();
    });

  }
Run Code Online (Sandbox Code Playgroud)

组件代码:

export class ErrorsListBottomSheetComponent implements OnInit {
  overlayRef: OverlayRef; -- REMOVE THIS--

  constructor(
-- ADD SOMETHING HERE --
  ) {}

close() {
    if (this.overlayRef) {
      this.overlayRef.detach();
    }
  }
Run Code Online (Sandbox Code Playgroud)

更好的是,是否有类似的叠加

<button mat-dialog-close>close</button>
Run Code Online (Sandbox Code Playgroud)

代替

<button (click)="close()">close</button>
Run Code Online (Sandbox Code Playgroud)

Pra*_*ore 8

您可以使用@Ouput 事件发射器从组件发出事件,然后在服务中订阅它。

组件代码:

export class ErrorsListBottomSheetComponent implements OnInit {
  @Output() closePanel = new EventEmitter<void>();

  ...

  close() {
    this.closePanel.emit();
  }
}
Run Code Online (Sandbox Code Playgroud)

服务代码:

display() {
   ...
   this.ref = overlayRef.attach<ErrorsListBottomSheetComponent>(portal);
   this.ref.instance.closePanel.subscribe(() => overlayRef.detach());
}
Run Code Online (Sandbox Code Playgroud)

html代码:

<button (click)="close()">Close</button>
Run Code Online (Sandbox Code Playgroud)


小智 1

尝试这样

constructor(private _bottomSheetRef: MatBottomSheetRef<?>, private _bottomSheet: MatBottomSheet) {
}

close() {
  this._bottomSheet.dismiss()
}

// Here MatBottomSheetRef<?> ? is your component
Run Code Online (Sandbox Code Playgroud)