Angular6 open/show 服务组件

Angular6 open/show component by service

我构建了一个 angular 组件用作我的应用程序的对话框(例如显示应用程序错误)和一个对话框-服务 到 open/show来自其他组件的对话框。

dialog.component.html

<kendo-dialog *ngIf="opened">
  <div>
    Some Content
  </div>
</kendo-dialog>

dialog.compontent.ts

import { Component, OnInit } from '@angular/core';
import { Dialog } from './dialog'; // Model

@Component({
  selector: 'dialog',
  templateUrl: './dialog.component.html',
  styleUrls: ['./dialog.component.scss']
})
export class DialogComponent implements OnInit {
  public opened = false;
  public dialog: Dialog; // Contains properties like title, message

  constructor() {
  }

  ngOnInit() {}

  public showDialog(dialog: Dialog) {
    this.dialog = dialog;
    this.opened = true;
  }
}

dialog.service.ts

import { Injectable } from '@angular/core';
import { Dialog } from './dialog';

@Injectable()
export class DialogService {
  constructor() {}

  public showDialog(
    title: string,
    message: string,
    isConfirm: boolean,
    icon?: string
  ) {
    const dialog = new Dialog(title, message, isConfirm, icon);

    // TODO: Open/Show Dialog Component with DialogService
    // set opened property from DialogComponent = true
  }
}

我需要在 DialogService 中做什么才能从任何地方显示我的 DialogComponent? 例如,我在某处有一个 try/catch 块,想用 DialogComponent:

显示错误消息
try {
// Do something
} catch(error => {
    this.dialogService.showDialog('Title', error.Message, true);
})

您应该使用 Angular CDK Overlay

它允许您创建具有一定不透明度的背景,在其上动态注入组件,并配置位置策略和滚动策略。

让我为您提供一些可以帮助您入门的代码:

constructor(
   private overlay: Overlay,
   private componentFactoryResolver: ComponentFactoryResolver
) {}

let componentFactory = this.componentFactoryResolver.resolveComponentFactory(DialogComponent);

const overlayRef = this.overlay.create(
  {
    hasBackdrop: true,
    positionStrategy: this.overlay.position().global().centerHorizontally().centerVertically()
  }
);

overlayRef.backdropClick().subscribe(res => {
  overlayRef.detach();
});

let portal = new ComponentPortal(componentFactory.componentType);

let component = overlayRef.attach<DialogComponent>(portal);

component.instance.onCloseClick.subscribe(() => {
  overlayRef.detach();
});