Angular 2: NgbModal transclude in view

大城市里の小女人 提交于 2019-12-08 18:51:16

问题


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:


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


来源:https://stackoverflow.com/questions/44359094/angular-2-ngbmodal-transclude-in-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!