Issue
I have a modal wrapped in ng-template,
<ng-template #template>
<div class="modal-header">
<h4 class="modal-title pull-left">Modal for user id : {{ modalService.config.initialState.id }}</h4>
<button type="button" class="close pull-right" aria-label="Close" (click)="modalRef.hide()">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
This is a modal.
</div>
</ng-template>
i have a button to open this modal like
<button type="button" class="btn btn-primary" (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?
Solution
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
});
}
https://stackblitz.com/edit/angular-modal-bootstap-pay2ua?file=app%2Fapp.component.ts
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
})
})
https://stackblitz.com/edit/angular-modal-bootstap-pr377t?file=app/app.component.ts
Answered By - Ashish Ranjan
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.