I'm trying to create a common modal component for the application using BsModalService. This component will have different methods which contains different title and config. and that can be used from any other components.
Modal component ts file.
import { Component, OnInit, AfterViewInit, } from '@angular/core';
import { BsModalRef,BsModalService } from 'ngx-bootstrap';
@Component({
selector: 'app-modal',
templateUrl: './app-modal.component.html',
styleUrls: ['./app-modal.component.scss'],
})
export class AppModalComponent implements OnInit, AfterViewInit {
public modalRef: BsModalRef;
constructor(private modalService: BsModalService) {
console.log(`ngAfterViewInit - modaldiretive is---`);
}
ngOnInit() {
}
confirmationModal(){
const initialState = {
title: 'Confirmation',
message:'Are you sure, you want to delete this campaign?'
};
this.modalRef = this.modalService.show(AppModalComponent, {
class: 'modal-dialog-centered', ignoreBackdropClick :true,initialState
});
}
**close(){
this.modalRef.hide();
}**
ngAfterViewInit() {
console.log(`ngAfterViewInit - modaldiretive is ${this}`);
}
}
html.
<div class="modal-header">
<h4 class="modal-title pull-left">{{title}}</h4>
<button type="button" class="close pull-right" aria-label="Close" (click)="close()">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
{{message}}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" (click)="close()">Yes</button>
<button type="button" class="btn btn-default" (click)="close()">No</button>
</div>
Using in some other component. other.component.ts
import { Component } from '@angular/core';
import { BsModalRef, BsModalService } from 'ngx-bootstrap';
import { AppModalComponent } from 'app/core/modal/app-modal.component';
@Component({
selector: 'details',
templateUrl: './details.component.html',
styleUrls: ['./details.component.scss']
})
export class DetailsComponent{
constructor() {
}
removeDetails() {
this.appModal.confirmationModal();
}
}
On click of removeDetails in other component i'm able to get the confirmation modal but when closing it throws error this.modalRef is undefined; Can some one help me how to fix this and if my approach is correct to isolate my modalComponent and other component.**