我以两种不同的方式Stackblitz Example打开一个模态:
在调用模态服务的组件中调用方法:
<button (click)="openModal()">Open Modal</button>
export class AppComponent {
constructor(private modalService: ModalService) { }
openModal() {
this.modalService.open(HelloComponent);
}
}
Modal服务会动态创建组件。
使用指令,然后调用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 ]
})
所以我不确定为什么这不起作用...
答案 0 :(得分:1)
您需要为对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>
更新后的堆叠闪电战:https://stackblitz.com/edit/mk-angular-modal-service-bzn8z7?file=src%2Fapp%2Fapp.component.html