how to open ng-template modal from component?
Sebastian Wright
I have a modal wrapped in ng-template,
<ng-template #template> <div> <h4>Modal for user id : {{ modalService.config.initialState.id }}</h4> <button type="button" aria-label="Close" (click)="modalRef.hide()"> <span aria-hidden="true">×</span> </button> </div> <div> This is a modal. </div>
</ng-template>i have a button to open this modal like
<button type="button" (click)="openModal(template)">Create template modal</button>
openModal(template: TemplateRef<any>) { const user = { id: 10 }; this.modalRef = this.modalService.show(template, { initialState : user }); }this will work as i am passing template as a parameter.
How can i open this modal without passing the parameter? let it be i dont have a button, i want to open the modal on ngOninit. How it is possible?
14 Answers
Get the reference of the template in typescript using @ViewChild() decorator and use ngAfterViewInit() hook to open the modal..
@ViewChild('template') templateRef: TemplateRef<any>;
ngAfterViewInit() { const user = { id: 10 }; this.modalRef = this.modalService.show(this.templateRef, { initialState : user });
}Edit
I just noticed that we would be getting an ExpressionChangedAfterItHasBeenCheckedError if we show it in ngAfterViewInit() hook, to fix that wrap opening the modal in a setTimeuut()
setTimeout(() => { this.modalRef = this.modalService.show(this.templateRef, { initialState : user }) }) You can use ViewChild decorator to get the reference and to load initially use AfterViewInit hook which called after Angular has fully initialized a component's view.
import { Component,TemplateRef, OnInit,ViewChild,ElementRef, AfterViewInit } from '@angular/core';
@Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit, AfterViewInit { ngAfterViewInit() { const user = { id: 10 }; this.modalRef = this.modalService.show(this.template, { initialState : user }); }
} There's a very simple method to open <ng-template> </ng-template> modal in angular.
You can use modalService to open the modal, add below in .ts-file .
step 1: import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
step 2: constructor(private modalService: NgbModal)
step 3:
function openModal(template) { this.modalService.open(template); }When the button will be pressed, the function openModal() will be
triggered and the 'template' parameter will pass as an argument. This
in turn will trigger the modalService and open the modal 'template'.
In Angular is simple way of ng-template modal from component
like bellow
import NgbModal :
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
export class YourComponent implements OnInit {
constructor( private modalService: NgbModal ) {} ngOnInit(): void { this.openModal('template'); }
openModal(template) { this.modalService.open(template);
}
}