如何在组件中引用ng-template

时间:2019-10-11 11:53:19

标签: javascript html angular ng-template

如何在我的component.ts文件中引用<ng-template #modal_Template>。以前,我是通过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 个答案:

答案 0 :(得分:1)

您不需要获取nativeElement.value

如果模板中只有一个ng-template,则可以使用@Sam提供的方式来代替模板引用变量。

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

someFunctionEvent(){
  this.openModal(this.modalTemp);
}

答案 1 :(得分:-1)

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

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

可以在这里的文档中找到更多信息-https://angular.io/api/core/ViewChild#description