angular - 通过 Modal Service 向 Component 传递数据
问题描述
我在 Angular 7 StackBlitz 示例中有一个模态服务,用作:
export class AppComponent {
constructor(private modalService: ModalService) { }
openModal() {
this.modalService.open({
component: HelloComponent
});
}
}
export class HelloComponent extends Modal {
@Input property: string;
}
如何通过 Modal Service 与 HelloComponent 共享数据?
this.modalService.open(HelloComponent, { property: 'hello' });
不知道如何改变我的服务来实现这一点。我想在:
this.componentRef = this.componentFactoryResolver.resolveComponentFactory(component.component).create(this.injector);
this.componentRef.instance.modal = this;
this.appRef.attachView(this.componentRef.hostView);
return (this.componentRef.hostView as EmbeddedViewRef<any>).rootNodes[0] as HTMLElement;
模态服务
import { ApplicationRef, ComponentFactoryResolver, EmbeddedViewRef, Injectable, Injector } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class ModalService {
private componentRef: any;
private modalContainer: any;
constructor(
private componentFactoryResolver: ComponentFactoryResolver,
private appRef: ApplicationRef,
private injector: Injector) { }
private createFormModal(component: any): Element {
this.componentRef = this.componentFactoryResolver.resolveComponentFactory(component.component).create(this.injector);
this.componentRef.instance.modal = this;
this.appRef.attachView(this.componentRef.hostView);
return (this.componentRef.hostView as EmbeddedViewRef<any>).rootNodes[0] as HTMLElement;
}
open(component: any): void {
const alertElement = this.createFormModal(component);
const content = document.createElement('div');
content.classList.add('modal');
content.appendChild(alertElement);
this.modalContainer = document.createElement('div');
this.modalContainer.classList.add('modal');
this.modalContainer.appendChild(content);
document.body.appendChild(this.modalContainer);
}
close(): void {
this.appRef.detachView(this.componentRef.hostView);
this.modalContainer.parentNode.removeChild(this.modalContainer);
this.componentRef.destroy();
}
}
解决方案
看起来您正在尝试创建自己的模态类/服务。作为参考,我建议您在项目中使用 ng-bootstrap 模态对话框,然后探索 NgbActiveModal 类的设计方式。
推荐阅读
- jquery - 制表符 JSON 从服务器返回
- php - 将变量设置为 $_GET 值时遇到问题
- python - 如何使用 Python 在 Watson Discovery 中过滤查询结果?
- javascript - 是否有多次分配 window[functionName] = functionName 的简写?
- sql-server - 外键断言的聚集索引扫描
- php - $DBSERVER 是什么以及如何在 config.php 中进行配置?
- angular - 如何在 Imgur API 中进行授权?
- pointers - 在 C 中初始化特定成员
- ms-access - MS Access 运行时错误 '3011 显示在一个代码中,但不在另一个代码中
- visual-studio - Visual Studio 部署包更改文件安全性