Angular 2: NgbModal视图中的转移

9
假设我有这样的模态框模板:
<div class="modal-header">
  <h3 [innerHtml]="header"></h3>
</div>

<div class="modal-body">
  <ng-content></ng-content>
</div>

<div class="modal-footer">
</div>

我从另一个组件调用这个模态框:


    const modalRef = this.modalService.open(MobileDropdownModalComponent, {
      keyboard: false,
      backdrop: 'static'
    });

    modalRef.componentInstance.header = this.text;

我该如何在NgbModal中使用带有绑定等的html? 可以将其放入ng-content中。

1
首先,虽然我怀疑这与您的问题无关,但您似乎正在模板中访问私有属性。 - jonrsharpe
必须是这样吗?<default-wrapper *ngIf="formWrapper" [userId]="userId"></default-wrapper> - H. Pauwelyn
1
可以将您的代码发布到 Plunker 上,使用一个无意义的 userId 或其他信息。 - trungk18
1
@ConnorsFan,我正在尝试将某些内容放入ng-content的HTML中,主要问题是:this.modalService无法与ng-content一起使用。清楚吗? - brabertaser19
1
NgbModal不支持在ng-content中进行投影。您可以使用ngTemplateOutlet,例如https://plnkr.co/edit/Txhhutr5iYAiczgB3sC8?p=preview - yurzui
显示剩余4条评论
1个回答

4

您可以从通过 open 方法返回的 NgbModalRef 获取对组件实例的引用,并在那里设置绑定。

以下是打开模态框的方法:

open() {
   const instance = this.modalService.open(MyComponent).componentInstance;
   instance.name = 'Julia';
 }

这是将在模态框中显示的组件,其中只有一个输入绑定

export class MyComponent {
   @Input() name: string;

   constructor() {
   }
 }

===

您也可以将templateRef作为输入传递。假设父组件有:

 <ng-template #tpl>hi there</ng-template>


 export class AppComponent {
   @ViewChild('tpl') tpl: TemplateRef<any>;

  constructor(private modalService: NgbModal) {
  }

 open() {
    const instance = 
    this.modalService.open(MyComponent).componentInstance;
     instance.tpl = this.tpl;
  }
}

和 MyComponent:

export class MyComponentComponent {
  @Input() tpl;

  constructor(private viewContainerRef: ViewContainerRef) {
  }

  ngAfterViewInit() {
     this.viewContainerRef.createEmbeddedView(this.tpl);
  }
}

1
它能处理像值、字符串等的输入,但我需要一个DOM!(ng-content) - brabertaser19
顺便说一下,在我的问题中,我正在使用componentInstance。 - brabertaser19

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接