Angular6打开/显示组件按服务

时间:2018-09-12 11:47:17

标签: angular kendo-ui components angular6 kendo-window

我构建了一个角度组件以用作我的应用程序的对话框(例如,显示应用程序错误),并创建了一个对话框服务,以从其他组件打开/显示该对话框。

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
  }
}

要在任何位置显示我的DialogComponent,我需要在DialogService中做什么? 例如,我在某处有一个try / catch块,想用DialogComponent显示错误消息:

try {
// Do something
} catch(error => {
    this.dialogService.showDialog('Title', error.Message, true);
})

1 个答案:

答案 0 :(得分:0)

您应该使用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();
});