Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

  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.

  2. 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);
    
      }
    
    }
    

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

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

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 ...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
254 views
Welcome To Ask or Share your Answers For Others

1 Answer

You need to alias the reference to HelloComponent.

Update app.component

export class AppComponent  {

  modalComp = HelloComponent;

  constructor(private modalService: ModalService) { }

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

}

and template:

<div style="text-align:center">
  <h1>Modal Example</h1>

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

  <button [modal]="modalComp">Open Modal</button>

</div>

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...