javascript - Angular 2: NgbModal görünümde transklüde etme


Diyelim ki böyle bir modal şablonum var:

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

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

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

ve bu modalı başka bir bileşenden çağırıyorum, bu yüzden:

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

    modalRef.componentInstance.header = this.text;

NgbModal içine bağlamalar vb. ile HTML'i nasıl ekleyebilirim? ng-content içine

Cevap #1

open metodundan dönen NgbModalRef üzerinden bileşen örneğine bir referans alabilir ve bağlamayı orada ayarlayabilirsiniz.

işte modalı açan yöntem:

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

ve işte bir girdi bağı ile modalde görüntülenecek bileşen

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

   constructor() {
   }
 }

===

Ayrıca bir templateRef’i giriş olarak geçirebilirsiniz. Diyelim ki ana bileşen şuna sahip

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

ve MyComponent:

export class MyComponentComponent {
  @Input() tpl;

  constructor(private viewContainerRef: ViewContainerRef) {
  }

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

İlgili makaleler