Angular 2: NgbModal transclude in view

1.6k Views Asked by At

Let's say i have such modal template:

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

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

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

and i'm calling this modal from another component so:


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

    modalRef.componentInstance.header = this.text;

How can i put into NgbModal html with bindings etc? Into ng-content

1

There are 1 best solutions below

2
On

You can get a reference to the component instance from NgbModalRef returned by open method and set the binging there.

here is method that open the modal:

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

and here is the component that will be displayed in the modal with one input binding

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

   constructor() {
   }
 }

===

You can pass a templateRef as input as well. Let say the parent component has

 <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;
  }
}

and MyComponent:

export class MyComponentComponent {
  @Input() tpl;

  constructor(private viewContainerRef: ViewContainerRef) {
  }

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