angular - @NgModule.entryComponents 和动态创建的组件
问题描述
我以两种不同的方式打开模态Stackblitz 示例:
在调用模态服务的组件中调用方法:
<button (click)="openModal()">Open Modal</button> export class AppComponent { constructor(private modalService: ModalService) { } openModal() { this.modalService.open(HelloComponent); } }
模态服务动态创建组件。
使用然后调用 ModalService 的指令:
<button [modal]="'HelloComponent'">Open Modal</button> @Directive({ selector: '[modal]' }) export class ModalDirective { @Input('modal') identifier: string; constructor(private modalService: ModalService) { } @HostListener('click', ['$event']) clickEvent(event) { event.preventDefault(); event.stopPropagation(); this.modalService.open(this.identifier); } }
选项 (1) 工作正常,但选项 (2) 返回错误:
Error: No component factory found for HelloComponent. Did you add it to @NgModule.entryComponents?
我的 AppModule 中有以下内容:
@NgModule({
imports: [ BrowserModule, FormsModule ],
exports: [ ModalDirective ],
declarations: [ AppComponent, HelloComponent, ModalDirective ],
entryComponents: [HelloComponent],
bootstrap: [ AppComponent ]
})
所以我不确定为什么这不起作用......
解决方案
您需要将引用别名为HelloComponent
.
更新app.component
export class AppComponent {
modalComp = HelloComponent;
constructor(private modalService: ModalService) { }
openModal() {
this.modalService.open(this.modalComp);
}
}
和模板:
<div style="text-align:center">
<h1>Modal Example</h1>
<button (click)="openModal()">Open Modal</button>
<button [modal]="modalComp">Open Modal</button>
</div>
更新堆栈闪电战:https ://stackblitz.com/edit/mk-angular-modal-service-bzn8z7?file=src%2Fapp%2Fapp.component.html
推荐阅读
- matlab - 对 roi 进行边缘检测
- android - Android使用指定帐户意图打开谷歌驱动器
- java - 单击默认全屏按钮后,如何使 JFrame 全屏显示?
- javascript - 谷歌图表错误 - 给定轴上的所有系列必须是相同的数据类型×
- php - SilverStripe 4 - 将上传的文件保存为成员扩展属性
- c++ - C++ 中的研究案例。抽象类和实例
- swift - Currying func 并在 Swift 4 中保留参数名称/标签
- python - 通过用列表替换单元格值来扩展熊猫数据框
- spring - 推送到 GIT 时如何加密或保护密钥?
- node.js - 如何使用node js仅在设备温度大于25或小于19时发送一次警告消息