Angular6 открыть / показать компонент по сервису - PullRequest
0 голосов
/ 12 сентября 2018

Я создал угловой компонент для использования в качестве диалога для моего приложения (например, для отображения ошибок приложения) и диалогового окна - service для открытия / отображения этого диалога из других компонентов.

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

1 Ответ

0 голосов
/ 12 сентября 2018

Вы должны использовать 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();
});
...