首页 > 解决方案 > @NgModule.entryComponents 和动态创建的组件

问题描述

我以两种不同的方式打开模态Stackblitz 示例

  1. 在调用模态服务的组件中调用方法:

    <button (click)="openModal()">Open Modal</button>
    
    export class AppComponent  {
    
      constructor(private modalService: ModalService) { }
    
      openModal() {
        this.modalService.open(HelloComponent);
      }
    
    }
    

    模态服务动态创建组件。

  2. 使用然后调用 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 ]
})

所以我不确定为什么这不起作用......

标签: angularangular6angular7

解决方案


您需要将引用别名为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


推荐阅读