gpt4 book ai didi

angular - Angular 7 的简单 ModalService 打不开 : No component factory found for

转载 作者:行者123 更新时间:2023-12-02 09:09:15 29 4
gpt4 key购买 nike

我正在创建一个 Angular 的 7 ModalService,它只打开一个模态 (StackBlitz Example)。

模态内容应该是打开时传递给模态的组件。

模态

export class Modal {

protected modal: any = null;

close() {
this.modal.close();
}

}

模态服务

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

}

我不确定这是否是最佳选择,但它不起作用......

当我尝试打开模式时,出现以下错误:

Error: No component factory found for HelloComponent. 
Did you add it to Did you add it to @NgModule.entryComponents?

我错过了什么?我可以改进这个 ModalService 代码吗?

最佳答案

如错误所示,如果您需要将组件呈现为模态内容。这是必需的,因为根据 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 { }

这是更新后的 stackblitz 演示 -

https://stackblitz.com/edit/mk-angular-modal-service-6qhrps

这里是关于entryComponents的更多信息

https://angular.io/guide/entry-components

您的模式中仍有一些 CSS 问题需要修复。

关于angular - Angular 7 的简单 ModalService 打不开 : No component factory found for,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54558428/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com