Angular 2:NgbModal在视野中转换

bra*_*r19 7 javascript typescript ng-bootstrap ng-modal angular

假设我有这样的模态模板:

<div class="modal-header">
  <h3 [innerHtml]="header"></h3>
</div>

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

<div class="modal-footer">
</div>
Run Code Online (Sandbox Code Playgroud)

我从另一个组件调用这个模态,所以:


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

    modalRef.componentInstance.header = this.text;
Run Code Online (Sandbox Code Playgroud)

我怎么能用NgbModal绑定等放入html?成ng-content

Jul*_*ova 4

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

这是打开模式的方法:

open() {
   const instance = this.modalService.open(MyComponent).componentInstance;
   instance.name = 'Julia';
 }
Run Code Online (Sandbox Code Playgroud)

这是将通过一个输入绑定显示在模式中的组件

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

   constructor() {
   }
 }
Run Code Online (Sandbox Code Playgroud)

===

您也可以传递 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;
  }
}
Run Code Online (Sandbox Code Playgroud)

和我的组件:

export class MyComponentComponent {
  @Input() tpl;

  constructor(private viewContainerRef: ViewContainerRef) {
  }

  ngAfterViewInit() {
     this.viewContainerRef.createEmbeddedView(this.tpl);
  }
}
Run Code Online (Sandbox Code Playgroud)