@ NgModule.entryComponents和动态创建的组件 [英] @NgModule.entryComponents and Components created dynamically

查看:92
本文介绍了@ NgModule.entryComponents和动态创建的组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am opening a Modal in two different ways Stackblitz Example:

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

  1. Calling a method in a component which calls the Modal Service:

<button (click)="openModal()">Open Modal</button>

export class AppComponent  {

  constructor(private modalService: ModalService) { }

  openModal() {
    this.modalService.open(HelloComponent);
  }

}

模态服务会动态创建组件.

The Modal service creates the component dynamically.

使用随后调用ModalService的指令:

Using a directive that then calls the 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)返回错误:

Option (1) works fine but option (2) returns an error:

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

我的AppModule中具有以下内容:

I have in my AppModule the following:

@NgModule({
  imports:      [ BrowserModule, FormsModule ],
  exports:      [ ModalDirective ],
  declarations: [ AppComponent, HelloComponent, ModalDirective ],
  entryComponents: [HelloComponent],
  bootstrap:    [ AppComponent ]
})

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

So I am not sure why this is not working ...

推荐答案

您需要为对HelloComponent的引用添加别名.

You need to alias the reference to 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

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

这篇关于@ NgModule.entryComponents和动态创建的组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆