【问题标题】:Angular6 open/show component by serviceAngular6按服务打开/显示组件
【发布时间】:2018-09-12 11:47:17
【问题描述】:

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

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

【问题讨论】:

  • 你是什么意思?如果你想使用该组件,只需在任何你想要的地方调用它的选择器&lt;dialog #dialog&gt;&lt;/dialog&gt;&lt;button (click)="dialog.open();"&gt;&lt;/button&gt; 类似的东西
  • 我的意思是在错误处理程序和 catch 块中使用它,我可以用这样的方式显示它:catch(error =&gt; { this.dialogService.showDialog('ErrorTitle', error.Message'); })
  • 您可以在任何地方使用您的组件,只需调用它的选择器并向其添加模板名称,以便您可以在 try catch 块或任何其他块中使用。&lt;dialog #dialog&gt;&lt;/dialog&gt; 和组件内部 @ViewChild('dialog') dialog: MyDialogComponent; 和终于catch(error =&gt; { this.dialog.showDialog('ErrorTitle', error.Message'); })

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


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-08
    • 1970-01-01
    • 1970-01-01
    • 2019-02-16
    • 2018-12-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多