我正在创建一个 Angular 的 7 ModalService,它只是打开一个 Modal(StackBlitz Example)。
Modal 内容应该是打开时传递给 Modal 的 Component。
模态
export class Modal {
protected modal: any = null;
close() {
this.modal.close();
}
}
Run Code Online (Sandbox Code Playgroud)
模态服务
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();
}
}
Run Code Online (Sandbox Code Playgroud)
我不确定这是否是最好的选择,但它不起作用......
当我尝试打开模态时,出现以下错误:
Error: No component factory found for HelloComponent.
Did you add it to Did you add it to @NgModule.entryComponents?
Run Code Online (Sandbox Code Playgroud)
我错过了什么?我可以改进这个 ModalService 代码吗?
正如错误所暗示的那样,如果您需要将组件呈现为模态内容,则需要将组件添加到entryComponents根模块的数组中app.module.ts。这是必需的,因为根据 angular 文档,如果您按类型命令性地(使用ComponentFactoryResolver)动态加载组件,那么您需要将该组件添加到entryComponents根模块的数组中。因为这些组件在你的 angular 应用程序中没有被模板或选择器引用。
所以你app.module.ts应该看起来像这样 -
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { HelloComponent } from './hello.component';
@NgModule({
imports: [ BrowserModule, FormsModule ],
declarations: [ AppComponent, HelloComponent ],
entryComponents:[HelloComponent],
bootstrap: [ AppComponent ]
})
export class AppModule { }
Run Code Online (Sandbox Code Playgroud)
这是更新的 stackblitz 演示 -
https://stackblitz.com/edit/mk-angular-modal-service-6qhrps
这里有更多信息 entryComponents
https://angular.io/guide/entry-components
您的模态中仍有一些 css 问题需要修复。
| 归档时间: |
|
| 查看次数: |
2940 次 |
| 最近记录: |