我用两种不同的方式打开一个模态Stackblitz Example:
<button (click)="openModal()">Open Modal</button>
export class AppComponent {
constructor(private modalService: ModalService) { }
openModal() {
this.modalService.open(HelloComponent);
}
}
Modal服务动态创建组件。<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 ]
})
所以我不确定为什么这不起作用......
您需要为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