问题
I am opening a Modal in two different ways Stackblitz Example:
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.
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 ...
回答1:
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
来源:https://stackoverflow.com/questions/55695980/ngmodule-entrycomponents-and-components-created-dynamically