Как ссылаться на ng-шаблон в компоненте - PullRequest
0 голосов
/ 11 октября 2019

Как мне сослаться на <ng-template #modal_Template> в моем файле component.ts. Раньше я вызывал модал через кнопку в моем html-файле и использовал это <button type="button" class="btn btn-primary" (click)="openModal(modal_Template)">Create template modal</button>, но теперь мне нужно вызвать его в моем файле компонента после запуска события. есть идеи как это сделать? Я попытался @ViewChild('modal_Template', {static: false}) modalTemp: ElementRef;, но это не сработало.

html:

<button type="button" class="btn btn-primary" (click)="openModal(modal_Template)">Create template modal</button>


<ng-template #modal_Template>
   //modal code  
</ng-template> 

файл компонента

import { Component, TemplateRef, OnInit, ViewChild, ElementRef } from '@angular/core';
import { BsModalService } from 'ngx-bootstrap/modal';
import { BsModalRef } from 'ngx-bootstrap/modal/bs-modal-ref.service';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
 @ViewChild('modal_Template', {static: false}) modalTemp: ElementRef;

  constructor(private modalService: BsModalService) { }
  //modal
  modalRef: BsModalRef;

  ngAfterViewInit() {
    console.log(this.modalTemp.nativeElement);
  }

  //modal func
  openModal(template: TemplateRef<any>) {
    this.modalRef = this.modalService.show(template,{ backdrop: 'static', keyboard: false });
  }


  //series of events
  someFunctionEvent(){
     //need to call modal function with the referenced #modal_Template variable as an argument
     this.openModal(this.modalTemp.nativeElement.value);
  }
}

Ответы [ 2 ]

1 голос
/ 11 октября 2019

Вам не нужно получать nativeElement.value.

Если в шаблоне только один ng-template, вы можете использовать способ, предоставленный @Sam, вместо ссылочной переменной шаблона.

@ViewChild('modal_Template', {static: false}) modalTemp: TemplateRef<void>;

someFunctionEvent(){
  this.openModal(this.modalTemp);
}
0 голосов
/ 11 октября 2019

@ViewChild(TemplateRef, {static: false}) template: TemplateRef<Object>;

<ng-template>Content</ng-template>

Вы можете найти больше в их документах здесь - https://angular.io/api/core/ViewChild#description

...