How do I reference <ng-template #modal_Template>
in my component.ts file. Previously, I called a modal via a button on my html file and used this <button type="button" class="btn btn-primary" (click)="openModal(modal_Template)">Create template modal</button>
but now I need to call it in my component file after an event is fired. Any idea how to do this? I tried @ViewChild('modal_Template', {static: false}) modalTemp: ElementRef;
but that doesn't seem to work.
html:
<button type="button" class="btn btn-primary" (click)="openModal(modal_Template)">Create template modal</button>
<ng-template #modal_Template>
//modal code
</ng-template>
component file
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);
}
}
You do not need to get nativeElement.value
.
If there is only one ng-template
in the template, you can use the way provided by @Sam instead of the template reference variable.
@ViewChild('modal_Template', {static: false}) modalTemp: TemplateRef<void>;
someFunctionEvent(){
this.openModal(this.modalTemp);
}