[英]How to reference ng-template in component
如何在我的 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);
}
}
您不需要獲取nativeElement.value
。
如果模板中只有一個ng-template
,可以使用@Sam 提供的方式代替模板引用變量。
@ViewChild('modal_Template', {static: false}) modalTemp: TemplateRef<void>;
someFunctionEvent(){
this.openModal(this.modalTemp);
}
@ViewChild(TemplateRef, {static: false}) template: TemplateRef<Object>;
<ng-template>Content</ng-template>
可以在他們的文檔中找到更多信息 - https://angular.io/api/core/ViewChild#description
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.