@ NgModule.entryComponents和动态创建的组件

问题描述 投票:-1回答:1

我用两种不同的方式打开一个模态Stackblitz Example

  1. 在调用模态服务的组件中调用方法: <button (click)="openModal()">Open Modal</button> export class AppComponent { constructor(private modalService: ModalService) { } openModal() { this.modalService.open(HelloComponent); } } Modal服务动态创建组件。
  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 ]
})

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

angular angular6 angular7
1个回答
2
投票

您需要为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>

更新了stackblitz:https://stackblitz.com/edit/mk-angular-modal-service-bzn8z7?file=src%2Fapp%2Fapp.component.html

© www.soinside.com 2019 - 2024. All rights reserved.