首页 > 解决方案 > 如何在Angular 6中的Ngx-bootstrap模态中将组件作为模态体传递

问题描述

我在 Angular 6 中将 ngx-bootstrap 用于模态,我创建了一个共享模态,我想在模态正文部分添加不同的 Html 模板。如何添加 HTML 模板或如何将动态组件传递给共享模式。

共享模态组件:

@Component({
selector: 'modal-content',
template: `
<div class="modal-header">
  <h4 class="modal-title">{{headerText}}</h4>
</div>
  <div *ngIf="showTemplate" class="modal-body">
   <templateselector></templateselector>
 </div>
<div class="modal-footer">
  <button  type="button" class="btn btn-primary" (click)="clickOk()"> 
  {{actionButtonText}}</button>
</div>
`
 })
export class ModalContentComponent{
 headerText: string; 
 actionButtonText: string;
 showTemplate: boolean;
 templateselector: any;  

 constructor(public bsModalRef: BsModalRef) { }

 clickOk() {
    this.bsModalRef.hide();
 }

调用组件:

@Component({
selector: 'modal-content',
template: `
   <div>
  <button type="button" class="btn" 
  (click)="openModalWithComponent()">modal</button>
   </div>`
  })

export class DynamicComponent{

constructor(public bsModalRef: BsModalRef) { }

openModalWithComponent(message: string, title: string) {
    const initialState = {
        headerText: title, 
        actionButtonText: "Continue",
        showTemplate: true,
        templateSelector : NewComponent //From here i need to pass different 
        //HTML which should get load in Modal body.
};
    this.bsModalRef = this.modalService.show(ModalContentComponent, { 
    initialState });

}

从调用组件我应该能够传递组件的名称,我不想对选择器进行硬编码,因为该组件将发生变化,并且应该加载该组件以及模态页眉和页脚。

标签: angularngx-bootstrap-modal

解决方案


代替

this.bsModalRef = this.modalService.show(ModalContentComponent, { initialState });

您可能想要删除括号并仅使用该对象作为第二个参数:

this.bsModalRef = this.modalService.show(ModalContentComponent, initialState);

推荐阅读