Angular TemplateRef 问题
Angular TemplateRef Issue
我必须将所有 ngx-bootstrap modals
放在一个 component.html
中,这样我就可以从任何地方访问任何模式。
我在
中尝试了以下代码
header.componentn.html
<button (click)="Login(loginModal)">Login</button>
header.cmponent.ts
@Input() myModal: AppModalsComponent;
bsModalRef: BsModalRef;
Login(template:TemplateRef<any>) {
this.myModal.openModal(template);
}
app-modals.component.html
<ng-template #loginModal>
<div class="modal-body">Login Here</div>
</ng-template>
app-modals.component.ts
openModal(template: TemplateRef<any>) {
this.modalRef = this.modalService.show(template, this.config);
}
完整代码位于 StackBlitz。
我正在传递来自 HTML 的模板引用对象。它在 ts
中变得不确定。我认为这是因为相应的 ng-template 不存在于同一个 HTML 中。
如何解决这个问题?
根据您在模态服务上调用 show()
和
的文档
Pass a TemplateRef or a component as a first argument and config as a second (optionally).
为了更轻松地共享这些模态框,我会让每个模态框成为它自己的组件。您需要确保在 app.module
.
中将其声明为 entryComponent
然后在任何需要打开模态的组件中,您只需注入模态服务,然后传递您希望它创建的 ModalComponent。
modal.component.ts
@Component({
selector: 'app-modal',
template: '<div class="modal-body">Login Here</div>'
})
export class ModalComponent {}
some.componet.ts
@Component({
selector: 'app-some',
template: '<button (click)="openModal">Open the modal</button>'
})
export class SomeComponent {
constructor(public modalService: BsModalService) { }
openModal() {
this.modalService.show(ModalComponent);
}
}
Stackblitz
我必须将所有 ngx-bootstrap modals
放在一个 component.html
中,这样我就可以从任何地方访问任何模式。
我在
中尝试了以下代码header.componentn.html
<button (click)="Login(loginModal)">Login</button>
header.cmponent.ts
@Input() myModal: AppModalsComponent;
bsModalRef: BsModalRef;
Login(template:TemplateRef<any>) {
this.myModal.openModal(template);
}
app-modals.component.html
<ng-template #loginModal>
<div class="modal-body">Login Here</div>
</ng-template>
app-modals.component.ts
openModal(template: TemplateRef<any>) {
this.modalRef = this.modalService.show(template, this.config);
}
完整代码位于 StackBlitz。
我正在传递来自 HTML 的模板引用对象。它在 ts
中变得不确定。我认为这是因为相应的 ng-template 不存在于同一个 HTML 中。
如何解决这个问题?
根据您在模态服务上调用 show()
和
Pass a TemplateRef or a component as a first argument and config as a second (optionally).
为了更轻松地共享这些模态框,我会让每个模态框成为它自己的组件。您需要确保在 app.module
.
entryComponent
然后在任何需要打开模态的组件中,您只需注入模态服务,然后传递您希望它创建的 ModalComponent。
modal.component.ts
@Component({
selector: 'app-modal',
template: '<div class="modal-body">Login Here</div>'
})
export class ModalComponent {}
some.componet.ts
@Component({
selector: 'app-some',
template: '<button (click)="openModal">Open the modal</button>'
})
export class SomeComponent {
constructor(public modalService: BsModalService) { }
openModal() {
this.modalService.show(ModalComponent);
}
}