Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2: NgbModal transclude in view

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

like image 760
brabertaser19 Avatar asked Jun 04 '17 21:06

brabertaser19


1 Answers

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);
  }
}
like image 96
Julia Passynkova Avatar answered Oct 06 '22 04:10

Julia Passynkova